Completed
Push — master ( fc4ca4...d4b6e7 )
by
unknown
14s queued 11s
created

pagantis::getTaxId()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 9
rs 10
1
<?php
2
3
use Pagantis\ModuleUtils\Exception\OrderNotFoundException;
4
use Pagantis\OrdersApiClient\Model\Order\User\Address;
5
use Pagantis\ModuleUtils\Exception\UnknownException;
6
use Pagantis\ModuleUtils\Model\Log\LogEntry;
7
8
define('TABLE_PAGANTIS_LOG', 'pagantis_log');
9
define('TABLE_PAGANTIS_CONFIG', 'pagantis_config');
10
define('TABLE_PAGANTIS_ORDERS', 'pagantis_order');
11
define('TABLE_PAGANTIS_CONCURRENCY', 'pagantis_concurrency');
12
define('MODULE_PAYMENT_PAGANTIS_TEXT_ADMIN_TITLE', 'Pagantis');
13
define('__ROOT__', dirname(dirname(__FILE__)));
14
15
class pagantis
16
{
17
    /** @var  String $is_guest */
18
    public $is_guest;
19
20
    /** @var Array $extraConfig */
21
    public $extraConfig;
22
23
    /** @var String $form_action_url */
24
    public $form_action_url;
25
26
    /** @var String $base_url */
27
    public $base_url;
28
29
    /** @var String $os_order_reference */
30
    public $os_order_reference;
31
32
    /** @var notifyController $pgNotify */
33
    public $pgNotify;
34
35
    /** @var string $langCode */
36
    public $langCode = null;
37
38
    public $defaultConfigs = array('PAGANTIS_TITLE'=>'Instant Financing',
39
                                   'PAGANTIS_SIMULATOR_DISPLAY_TYPE'=>'pgSDK.simulator.types.SIMPLE',
40
                                   'PAGANTIS_SIMULATOR_DISPLAY_SKIN'=>'pgSDK.simulator.skins.BLUE',
41
                                   'PAGANTIS_SIMULATOR_DISPLAY_POSITION'=>'hookDisplayProductButtons',
42
                                   'PAGANTIS_SIMULATOR_START_INSTALLMENTS'=>3,
43
                                   'PAGANTIS_SIMULATOR_MAX_INSTALLMENTS'=>12,
44
                                   'PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'=>'default',
45
                                   'PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION'=>'pgSDK.simulator.positions.INNER',
46
                                   'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'=>'default',
47
                                   'PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'=>'default',
48
                                   'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR_CHECKOUT'=>'default',
49
                                   'PAGANTIS_FORM_DISPLAY_TYPE'=>0,
50
                                   'PAGANTIS_DISPLAY_MIN_AMOUNT'=>1,
51
                                   'PAGANTIS_URL_OK'=>'',
52
                                   'PAGANTIS_URL_KO'=>'',
53
                                   'PAGANTIS_TITLE_EXTRA' => 'Paga hasta en 12 cómodas cuotas con Paga+Tarde. Solicitud totalmente online y sin papeleos,¡y la respuesta es inmediata!',
54
                                   'PAGANTIS_PROMOTION' => '',
55
                                   'PAGANTIS_PROMOTED_PRODUCT_CODE' => '<p>¡Financia este producto sin intereses! - 0% TAE</p>'
56
    );
57
58
    /**
59
     * Constructor
60
     */
61
    public function __construct()
62
    {
63
        $this->version = '8.0.2';
0 ignored issues
show
Bug Best Practice introduced by
The property version does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
64
        $this->code = 'pagantis';
0 ignored issues
show
Bug Best Practice introduced by
The property code does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
65
        $this->sort_order = 0;
0 ignored issues
show
Bug Best Practice introduced by
The property sort_order does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
66
        $this->description = $this->getDescription();
0 ignored issues
show
Bug Best Practice introduced by
The property description does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
67
        $this->extraConfig = $this->getExtraConfig();
68
69
        if (strpos($_SERVER[REQUEST_URI], "checkout_payment.php") <= 0) {
0 ignored issues
show
Bug introduced by
The constant REQUEST_URI was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
70
            $this->title = MODULE_PAYMENT_PAGANTIS_TEXT_ADMIN_TITLE; // Payment module title in Admin
0 ignored issues
show
Bug Best Practice introduced by
The property title does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
71
        } else {
72
            $this->title = MODULE_PAYMENT_PAGANTIS_TEXT_CHECKOUT .'<br/><br/><div class="buttonSet" style="display:none"></div><br/>'; // Payment module title in Catalog
73
        }
74
75
        $this->enabled = ((MODULE_PAYMENT_PAGANTIS_STATUS == 'True') ? true : false);
0 ignored issues
show
Bug introduced by
The constant MODULE_PAYMENT_PAGANTIS_STATUS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug Best Practice introduced by
The property enabled does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
76
77
        $this->base_url = dirname(
78
            sprintf(
79
                "%s://%s%s%s",
80
                isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
81
                $_SERVER['SERVER_NAME'],
82
                isset($_SERVER['SERVER_PORT']) ? ":" . $_SERVER['SERVER_PORT'] : '',
83
                $_SERVER['REQUEST_URI']
84
            )
85
        );
86
87
        $this->form_action_url = $this->base_url . '/ext/modules/payment/pagantis/bypass.php';
88
89
        if (defined('MODULE_PAYMENT_PAGANTIS_LANG_CODE')) {
90
            $this->langCode = strtoupper(MODULE_PAYMENT_PAGANTIS_LANG_CODE);
91
        }
92
    }
93
94
    /***************
95
     *
96
     * CLASS METHODS
97
     *
98
     **************/
99
    /**
100
     * Here you can implement using payment zones (refer to standard PayPal module as reference)
101
     */
102
    public function update_status()
103
    {
104
105
    }
106
107
    /*
108
    * Here you may define client side javascript that will verify any input fields you use in the payment method
109
    * selection page. Refer to standard cc module as reference (cc.php).
110
    */
111
    public function javascript_validation()
112
    {
113
        return false;
114
    }
115
116
    /*
117
    * Llamada cuando el usuario esta en la pantalla de eleccion de tipo de pago
118
     * This function outputs the payment method title/text and if required, the input fields.
119
    *
120
    * Si hay un pedido generado previamente y no confirmado, se borra
121
    * Caso de uso:
122
    * - el usuario llega a la pantalla de confirmacion
123
    * - se genera el pedido (pero no se genera entrada en orders_status_history)
124
    * - el usuario decide realizar algun cambio en su compra antes de pasar a pagantis
125
    * - entra de nuevo en la pantalla de seleccion de tipo de pago (puede elegir otra forma de pago)
126
    * - se comprueba que no exista el pedido generado anteriormente
127
    * - se borra el pedido que se habia generado inicialmente. Ya no es valido
128
    *
129
    */
130
    public function selection()
131
    {
132
        return array('id' => $this->code, 'module' => $this->title);
133
    }
134
135
    /*
136
    * Use this function implement any checks of any conditions after payment method has been selected. You most probably
137
    *  don't need to implement anything here.
138
    */
139
    public function pre_confirmation_check()
140
    {
141
        return false;
142
    }
143
144
    /*
145
     * Implement any checks or processing on the order information before proceeding to payment confirmation. You most
146
    probably don't need to implement anything here.
147
    * Llamada cuando el usuario entra en la pantalla de confirmacion
148
    *
149
    * Se genera el pedido:
150
    * - con el estado predefinido para el modulo pagantis
151
    * - sin notificacion a cliente ni administrador
152
    * - no se borra el carrito asociado al pedido
153
    *
154
    */
155
    public function confirmation()
156
    {
157
        return false;
158
    }
159
160
    /**
161
     * Build the data and actions to process when the "Submit" button is pressed on the order-confirmation screen.
162
     * This sends the data to the payment gateway for processing.
163
     * (These are hidden fields on the checkout confirmation page)
164
     */
165
    public function process_button()
166
    {
167
        try {
168
            include_once('./ext/modules/payment/pagantis/vendor/autoload.php');
169
            global $order, $customer_id, $sendto, $billto, $cart, $languages_id, $currency, $currencies, $shipping,
170
                   $payment, $comments, $customer_default_address_id, $cartID;
171
            $global_vars = array();
172
            $global_vars['customer_id'] = serialize($customer_id);
173
            $global_vars['sendTo'] = serialize($sendto);
174
            $global_vars['billTo'] = serialize($billto);
175
            $global_vars['cart'] = serialize($cart);
176
            $global_vars['languages_id'] = serialize($languages_id);
177
            $global_vars['currency'] = serialize($currency);
178
            $global_vars['currencies'] = serialize($currencies);
179
            $global_vars['shipping'] = serialize($shipping);
180
            $global_vars['payment'] = serialize($payment);
181
            $global_vars['comments'] = serialize($comments);
182
            $global_vars['$customer_default_address_id'] = serialize($customer_default_address_id);
183
            $global_vars['cartID'] = serialize($cartID);
184
            $global_vars['sessiontoken'] = serialize($_SESSION['sessiontoken']);
185
186
            if (!isset($order)) {
187
                throw new UnknownException("Order not found");
188
            }
189
190
            $id_hash = time().serialize($order->products).''.serialize($order->customer).''.serialize($order->delivery);
191
            $this->os_order_reference = md5($id_hash);
192
            $_SESSION['order_id'] = $this->os_order_reference;
193
194
            $national_id = $this->getNationalId();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $national_id is correct as $this->getNationalId() targeting pagantis::getNationalId() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
195
            $tax_id = $this->getTaxId();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $tax_id is correct as $this->getTaxId() targeting pagantis::getTaxId() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
196
197
            $userAddress = new Address();
198
            $userAddress
199
                ->setZipCode($order->billing['postcode'])
200
                ->setFullName($order->billing['firstname'] . ' ' . $order->billing['lastname'])
201
                ->setCountryCode('ES')
202
                ->setCity($order->billing['city'])
203
                ->setAddress($order->billing['street_address'])
204
                ->setFixPhone($order->customer['telephone'])
205
                ->setMobilePhone($order->customer['telephone'])
206
                ->setNationalId($national_id)
207
                ->setTaxId($tax_id);
208
209
            $orderBillingAddress = $userAddress;
210
211
            $orderShippingAddress = new Address();
212
            $orderShippingAddress
213
                ->setZipCode($order->delivery['postcode'])
214
                ->setFullName($order->billing['firstname'] . ' ' . $order->billing['lastname'])
215
                ->setCountryCode('ES')
216
                ->setCity($order->delivery['city'])
217
                ->setAddress($order->delivery['street_address'])
218
                ->setFixPhone($order->customer['telephone'])
219
                ->setMobilePhone($order->customer['telephone']);
220
221
            $orderUser = new \Pagantis\OrdersApiClient\Model\Order\User();
222
            $orderUser
223
                ->setAddress($userAddress)
224
                ->setFullName($order->billing['firstname'] . ' ' . $order->billing['lastname'])
225
                ->setBillingAddress($orderBillingAddress)
226
                ->setEmail($order->customer['email_address'])
227
                ->setFixPhone($order->customer['telephone'])
228
                ->setMobilePhone($order->customer['telephone'])
229
                ->setShippingAddress($orderShippingAddress)
230
                ->setNationalId($national_id)
231
                ->setTaxId($tax_id);
232
233
            $previousOrders = $this->getOrders();
234
            foreach ((array)$previousOrders as $k => $previousOrder) {
235
                $orderHistory = new \Pagantis\OrdersApiClient\Model\Order\User\OrderHistory();
236
                $orderHistory
237
                    ->setAmount(intval(100 * $previousOrder['value']))
238
                    ->setDate(new \DateTime($previousOrder['date_purchased']));
0 ignored issues
show
Bug introduced by
new DateTime($previousOrder['date_purchased']) of type DateTime is incompatible with the type string expected by parameter $date of Pagantis\OrdersApiClient...OrderHistory::setDate(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

238
                    ->setDate(/** @scrutinizer ignore-type */ new \DateTime($previousOrder['date_purchased']));
Loading history...
239
                $orderUser->addOrderHistory($orderHistory);
240
            }
241
242
            $details = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details();
243
            $shippingCost = number_format($order->info['shipping_cost'], 2, '.', '');
244
            $details->setShippingCost(intval(strval(100 * $shippingCost)));
245
246
            $metadataOrder = new \Pagantis\OrdersApiClient\Model\Order\Metadata();
247
            $metadata = array(
248
                'oscommerce' => PROJECT_VERSION,
0 ignored issues
show
Bug introduced by
The constant PROJECT_VERSION was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
249
                'pagantis' => $this->version,
250
                'php' => phpversion()
251
            );
252
            foreach ($metadata as $key => $metadatum) {
253
                $metadataOrder->addMetadata($key, $metadatum);
254
            }
255
256
            $promotedAmount = 0;
257
            foreach ($order->products as $item) {
258
                $promotedProduct = $this->isPromoted($item);
259
                $product = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product();
260
                $product
261
                    ->setAmount(intval(100 * number_format(($item['final_price'] * $item['qty']), 2)))
262
                    ->setQuantity(intval($item['qty']))
263
                    ->setDescription($item['name']);
264
                if ($promotedProduct) {
265
                    $promotedAmount+=$product->getAmount();
266
                    $promotedMessage = $product->getDescription()."-Price:".$item['final_price']."-Qty:".$product->getQuantity();
267
                    $metadataOrder->addMetadata('promotedProduct', $promotedMessage);
268
                }
269
                $details->addProduct($product);
270
            }
271
272
            $orderShoppingCart = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart();
273
            $orderShoppingCart
274
                ->setDetails($details)
275
                ->setOrderReference($this->os_order_reference)
276
                ->setTotalAmount(intval($order->info['total'] * 100))
277
                ->setPromotedAmount($promotedAmount);
278
279
            $callback_url = $this->base_url.'/ext/modules/payment/pagantis/notify.php?order_id='.$this->os_order_reference;
280
            $checkoutProcessUrl = htmlspecialchars_decode(
281
                tep_href_link(FILENAME_CHECKOUT_PROCESS, "order_id=$this->os_order_reference&from=order", 'SSL', true)
0 ignored issues
show
Bug introduced by
The constant FILENAME_CHECKOUT_PROCESS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The function tep_href_link was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

281
                /** @scrutinizer ignore-call */ 
282
                tep_href_link(FILENAME_CHECKOUT_PROCESS, "order_id=$this->os_order_reference&from=order", 'SSL', true)
Loading history...
282
            );
283
284
            $cancelUrl = trim(tep_href_link(FILENAME_CHECKOUT_SHIPPING, '', 'SSL', false));
0 ignored issues
show
Bug introduced by
The constant FILENAME_CHECKOUT_SHIPPING was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
285
            if ($this->extraConfig['PAGANTIS_URL_KO']!='') {
286
                $koUrl = $this->extraConfig['PAGANTIS_URL_KO'];
287
            } else {
288
                $koUrl = $cancelUrl;
289
            }
290
291
            $orderConfigurationUrls = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Urls();
292
            $orderConfigurationUrls
293
                ->setCancel($cancelUrl)
294
                ->setKo($koUrl)
295
                ->setAuthorizedNotificationCallback($callback_url)
296
                ->setRejectedNotificationCallback($callback_url)
297
                ->setOk($checkoutProcessUrl);
298
299
300
            $orderChannel = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Channel();
301
            $orderChannel
302
                ->setAssistedSale(false)
303
                ->setType(\Pagantis\OrdersApiClient\Model\Order\Configuration\Channel::ONLINE);
304
            $orderConfiguration = new \Pagantis\OrdersApiClient\Model\Order\Configuration();
305
            $orderConfiguration
306
                ->setChannel($orderChannel)
307
                ->setUrls($orderConfigurationUrls)
308
                ->setPurchaseCountry($this->langCode)
309
            ;
310
311
            $orderApiClient = new \Pagantis\OrdersApiClient\Model\Order();
312
            $orderApiClient
313
                ->setConfiguration($orderConfiguration)
314
                ->setMetadata($metadataOrder)
315
                ->setShoppingCart($orderShoppingCart)
316
                ->setUser($orderUser);
317
318
            $publicKey = trim(MODULE_PAYMENT_PAGANTIS_PK);
0 ignored issues
show
Bug introduced by
The constant MODULE_PAYMENT_PAGANTIS_PK was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
319
            $secretKey = trim(MODULE_PAYMENT_PAGANTIS_SK);
0 ignored issues
show
Bug introduced by
The constant MODULE_PAYMENT_PAGANTIS_SK was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
320
            $orderClient = new \Pagantis\OrdersApiClient\Client($publicKey, $secretKey);
321
            $pagantisOrder = $orderClient->createOrder($orderApiClient);
322
            if ($pagantisOrder instanceof \Pagantis\OrdersApiClient\Model\Order) {
0 ignored issues
show
introduced by
$pagantisOrder is always a sub-type of Pagantis\OrdersApiClient\Model\Order.
Loading history...
323
                $url = $pagantisOrder->getActionUrls()->getForm();
324
                $this->insertRow($this->os_order_reference, $pagantisOrder->getId(), serialize($global_vars));
325
            } else {
326
                throw new OrderNotFoundException();
327
            }
328
329
            if ($url == "") {
330
                throw new UnknownException(_("No ha sido posible obtener una respuesta de Pagantis"));
331
            } else {
332
                $output = "\n";
333
                $output .= tep_draw_hidden_field("formUrl", $url) . "\n";
0 ignored issues
show
Bug introduced by
The function tep_draw_hidden_field was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

333
                $output .= /** @scrutinizer ignore-call */ tep_draw_hidden_field("formUrl", $url) . "\n";
Loading history...
334
                $output .= tep_draw_hidden_field("cancelUrl", $cancelUrl) . "\n";
335
                return $output;
336
337
            } //TODO IFRAME
338
        } catch (\Exception $exception) {
339
            $this->insertLog($exception);
340
            header('Location: '.$cancelUrl);
341
            exit;
342
        }
343
    }
344
345
    /**
346
     * @throws Exception
347
     */
348
    public function before_process()
349
    {
350
        include_once('./ext/modules/payment/pagantis/notifyController.php');
351
        $this->pgNotify = new notifyController();
352
        $this->pgNotify->setOscommerceOrderId($_GET['order_id']);
353
        $this->pgNotify->setOrigin(isset($_GET['from']) ? ($_GET['from']) : 'order');
354
        $this->pgNotify->processInformation();
355
    }
356
357
    /**
358
     * Post-processing activities
359
     *
360
     * @return boolean
361
     */
362
    public function after_process()
363
    {
364
        $this->pgNotify->confirmInformation();
365
    }
366
367
    /**
368
     * @return bool
369
     */
370
    public function output_error()
371
    {
372
        return false;
373
    }
374
375
    /**
376
     * @return mixed
377
     */
378
    public function check()
379
    {
380
        if (!isset($this->_check)) {
381
            $query = "select * from ".TABLE_CONFIGURATION." where configuration_key = 'MODULE_PAYMENT_PAGANTIS_STATUS'";
0 ignored issues
show
Bug introduced by
The constant TABLE_CONFIGURATION was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
382
            $check_query = tep_db_query($query);
0 ignored issues
show
Bug introduced by
The function tep_db_query was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

382
            $check_query = /** @scrutinizer ignore-call */ tep_db_query($query);
Loading history...
383
            $this->_check = tep_db_num_rows($check_query);
0 ignored issues
show
Bug introduced by
The function tep_db_num_rows was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

383
            $this->_check = /** @scrutinizer ignore-call */ tep_db_num_rows($check_query);
Loading history...
Bug Best Practice introduced by
The property _check does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
384
        }
385
        $this->installPagantisTables();
386
        return $this->_check;
387
    }
388
389
    /**
390
     * This is where you define module's configurations (displayed in admin).
391
     */
392
    public function install()
393
    {
394
        global $messageStack;
395
396
        if (defined('MODULE_PAYMENT_PAGANTIS_STATUS')) {
397
            tep_redirect(tep_href_link(FILENAME_MODULES, 'set=payment&module=pagantis', 'NONSSL'));
0 ignored issues
show
Bug introduced by
The function tep_redirect was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

397
            /** @scrutinizer ignore-call */ 
398
            tep_redirect(tep_href_link(FILENAME_MODULES, 'set=payment&module=pagantis', 'NONSSL'));
Loading history...
Bug introduced by
The constant FILENAME_MODULES was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The function tep_href_link was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

397
            tep_redirect(/** @scrutinizer ignore-call */ tep_href_link(FILENAME_MODULES, 'set=payment&module=pagantis', 'NONSSL'));
Loading history...
398
            return 'failed';
399
        }
400
401
        tep_db_query("insert into " . TABLE_CONFIGURATION . "
0 ignored issues
show
Bug introduced by
The function tep_db_query was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

401
        /** @scrutinizer ignore-call */ 
402
        tep_db_query("insert into " . TABLE_CONFIGURATION . "
Loading history...
Bug introduced by
The constant TABLE_CONFIGURATION was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
402
        (
403
            configuration_title,
404
            configuration_key,
405
            configuration_value,
406
            configuration_description,
407
            configuration_group_id,
408
            sort_order,
409
            set_function,
410
            date_added) 
411
        values 
412
        (
413
            'Enable module',
414
            'MODULE_PAYMENT_PAGANTIS_STATUS',
415
            'True',
416
            '',
417
            '6',
418
            '0',
419
            'tep_cfg_select_option(array(\'True\',
420
            \'False\'),
421
            ',
422
            now()
423
        )");
424
        tep_db_query("insert into " . TABLE_CONFIGURATION . "
425
        (
426
            configuration_title,
427
            configuration_key,
428
            configuration_value,
429
            configuration_description,
430
            configuration_group_id,
431
            sort_order,
432
            date_added
433
        ) 
434
        values 
435
        (
436
            'Public Key',
437
            'MODULE_PAYMENT_PAGANTIS_PK',
438
            '',
439
            'MANDATORY. You can get in your pagantis profile',
440
            '6',
441
            '0',
442
            now()
443
        )");
444
        tep_db_query("insert into " . TABLE_CONFIGURATION . "
445
        (
446
            configuration_title,
447
            configuration_key,
448
            configuration_value,
449
            configuration_description,
450
            configuration_group_id,
451
            sort_order,
452
            date_added
453
        ) 
454
        values 
455
        (
456
            'Secret Key',
457
            'MODULE_PAYMENT_PAGANTIS_SK',
458
            '',
459
            'MANDATORY. You can get in your pagantis profile',
460
            '6',
461
            '0',
462
            now()
463
        )");
464
        tep_db_query("insert into " . TABLE_CONFIGURATION . "
465
        (
466
            configuration_title,
467
            configuration_key,
468
            configuration_value,
469
            configuration_description,
470
            configuration_group_id,
471
            sort_order,
472
            set_function,
473
            date_added
474
        ) 
475
        values 
476
        (
477
            'Include simulator',
478
            'MODULE_PAYMENT_PAGANTIS_SIMULATOR',
479
            'True',
480
            'Do you want to include Pagantis simulator',
481
            '6',
482
            '3',
483
            'tep_cfg_select_option(array(\'True\',\'False\'), ',
484
            now())"
485
        );
486
        $this->installPagantisTables();
487
488
        $this->installSimulator();
489
    }
490
491
    /**
492
     * Create the neccesary tables for the module
493
     */
494
    private function installPagantisTables()
495
    {
496
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_LOG . " ( 
497
                          id int NOT NULL AUTO_INCREMENT, 
498
                          log text NOT NULL, 
499
                          createdAt timestamp DEFAULT CURRENT_TIMESTAMP, 
500
                          UNIQUE KEY id (id))";
501
        tep_db_query($sql);
0 ignored issues
show
Bug introduced by
The function tep_db_query was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

501
        /** @scrutinizer ignore-call */ 
502
        tep_db_query($sql);
Loading history...
502
503
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_CONFIG . " (
504
                            id int NOT NULL AUTO_INCREMENT, 
505
                            config varchar(60) NOT NULL, 
506
                            value varchar(200) NOT NULL, 
507
                            UNIQUE KEY id(id))";
508
        tep_db_query($sql);
509
510
        // check if table has records
511
        $check_query = tep_db_query("select value from " . TABLE_PAGANTIS_CONFIG);
512
        if (tep_db_num_rows($check_query) === 0) {
0 ignored issues
show
Bug introduced by
The function tep_db_num_rows was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

512
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($check_query) === 0) {
Loading history...
513
            foreach ((array)$this->defaultConfigs as $configKey => $configValue) {
514
                $query = "INSERT INTO " . TABLE_PAGANTIS_CONFIG . "
515
                (
516
                    config,
517
                    value
518
                ) 
519
                values 
520
                (
521
                    '$configKey',
522
                    '$configValue'
523
                )";
524
                tep_db_query($query);
525
            }
526
        }
527
528
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_ORDERS . " (
529
                            id int NOT NULL AUTO_INCREMENT, 
530
                            os_order_id varchar(50), 
531
                            os_order_reference varchar(50) NOT NULL,
532
                            pagantis_order_id varchar(50) NOT NULL, 
533
                            globals text,
534
                            UNIQUE KEY id(id))";
535
        tep_db_query($sql);
536
537
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_CONCURRENCY . " (
538
                            id varchar(50) NOT NULL,
539
                            `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
540
                            UNIQUE KEY id(id))";
541
        tep_db_query($sql);
542
    }
543
544
    /**
545
     * Standard functionality to uninstall the module.
546
     */
547
    public function remove()
548
    {
549
        $checkTable = tep_db_query("SHOW TABLES LIKE '" . TABLE_PAGANTIS_LOG . "'");
0 ignored issues
show
Bug introduced by
The function tep_db_query was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

549
        $checkTable = /** @scrutinizer ignore-call */ tep_db_query("SHOW TABLES LIKE '" . TABLE_PAGANTIS_LOG . "'");
Loading history...
550
        if (tep_db_num_rows($checkTable) > 0) {
0 ignored issues
show
Bug introduced by
The function tep_db_num_rows was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

550
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkTable) > 0) {
Loading history...
551
            tep_db_query("drop table " . TABLE_PAGANTIS_LOG);
552
        }
553
554
        $checkTable = tep_db_query("SHOW TABLES LIKE '" . TABLE_PAGANTIS_CONFIG . "'");
555
        if (tep_db_num_rows($checkTable) > 0) {
556
            tep_db_query("drop table " . TABLE_PAGANTIS_CONFIG);
557
        }
558
559
        $checkTable = tep_db_query("SHOW TABLES LIKE '" . TABLE_PAGANTIS_ORDERS . "'");
560
        if (tep_db_num_rows($checkTable) > 0) {
561
            tep_db_query("drop table " . TABLE_PAGANTIS_ORDERS);
562
        }
563
564
        $checkTable = tep_db_query("SHOW TABLES LIKE '" . TABLE_PAGANTIS_CONCURRENCY . "'");
565
        if (tep_db_num_rows($checkTable) > 0) {
566
            tep_db_query("drop table " . TABLE_PAGANTIS_CONCURRENCY);
567
        }
568
569
        tep_db_query("DELETE FROM ". TABLE_CONFIGURATION ." where configuration_key in ('MODULE_PAYMENT_PAGANTIS_STATUS','MODULE_PAYMENT_PAGANTIS_PK','MODULE_PAYMENT_PAGANTIS_SK')");
0 ignored issues
show
Bug introduced by
The constant TABLE_CONFIGURATION was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
570
571
        $query = "delete from " . TABLE_CONFIGURATION . " where configuration_key like '%_PAGANTIS_%'";
572
        tep_db_query($query);
573
574
        $this->uninstallSimulator();
575
    }
576
577
    /**
578
     * Internal list of configuration keys used for configuration of the module
579
     *
580
     * @return array
581
     */
582
    public function keys()
583
    {
584
        return array(
585
            'MODULE_PAYMENT_PAGANTIS_STATUS',
586
            'MODULE_PAYMENT_PAGANTIS_PK',
587
            'MODULE_PAYMENT_PAGANTIS_SK',
588
            'MODULE_PAYMENT_PAGANTIS_SIMULATOR'
589
        );
590
    }
591
592
    /**
593
     * @return array
594
     */
595
    private function getOrders()
596
    {
597
        $this->is_guest = 'true';
598
        if (trim($_SESSION['customer_id']) != '') {
599
            $this->is_guest = 'false';
600
            $query = sprintf(
601
                "select orders_total.value, orders.date_purchased from orders 
602
JOIN orders_status_history ON orders.orders_id=orders_status_history.orders_id 
603
JOIN orders_total ON orders.orders_id=orders_total.orders_id 
604
where orders.customers_id='%s' and orders_status_history.orders_status_id in ('2','3') 
605
and orders_total.class='ot_total'",
606
                $_SESSION['customer_id']
607
            );
608
609
            $response = array();
610
            $resultsSelect = tep_db_query($query);
0 ignored issues
show
Bug introduced by
The function tep_db_query was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

610
            $resultsSelect = /** @scrutinizer ignore-call */ tep_db_query($query);
Loading history...
611
            while ($orderRow = tep_db_fetch_array($resultsSelect)) {
0 ignored issues
show
Bug introduced by
The function tep_db_fetch_array was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

611
            while ($orderRow = /** @scrutinizer ignore-call */ tep_db_fetch_array($resultsSelect)) {
Loading history...
612
                $response[] = $orderRow;
613
            }
614
        }
615
616
        return $response;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $response does not seem to be defined for all execution paths leading up to this point.
Loading history...
617
    }
618
619
    /**
620
     * @param $orderId
621
     * @param $pagantisOrderId
622
     * @param $globalVars
623
     */
624
    private function insertRow($orderId, $pagantisOrderId, $globalVars)
625
    {
626
        $query = "select * from " . TABLE_PAGANTIS_ORDERS . " where os_order_reference='$orderId'";
627
        $resultsSelect = tep_db_query($query);
0 ignored issues
show
Bug introduced by
The function tep_db_query was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

627
        $resultsSelect = /** @scrutinizer ignore-call */ tep_db_query($query);
Loading history...
628
        $countResults = tep_db_num_rows($resultsSelect);
0 ignored issues
show
Bug introduced by
The function tep_db_num_rows was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

628
        $countResults = /** @scrutinizer ignore-call */ tep_db_num_rows($resultsSelect);
Loading history...
629
        if ($countResults == 0) {
630
            $query = "INSERT INTO " . TABLE_PAGANTIS_ORDERS . " 
631
                (os_order_reference, pagantis_order_id, globals) values ('$orderId', '$pagantisOrderId','$globalVars')";
632
        } else {
633
            $query = "UPDATE ".TABLE_PAGANTIS_ORDERS." set pagantis_order_id='$pagantisOrderId' 
634
                        where os_order_reference='$orderId'";
635
        }
636
        tep_db_query($query);
637
    }
638
639
    /**
640
     * @return array
641
     */
642
    private function getExtraConfig()
643
    {
644
        $checkTable = tep_db_query("SHOW TABLES LIKE '".TABLE_PAGANTIS_CONFIG."'");
0 ignored issues
show
Bug introduced by
The function tep_db_query was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

644
        $checkTable = /** @scrutinizer ignore-call */ tep_db_query("SHOW TABLES LIKE '".TABLE_PAGANTIS_CONFIG."'");
Loading history...
645
        $response = array();
646
        if (tep_db_num_rows($checkTable) > 0) {
0 ignored issues
show
Bug introduced by
The function tep_db_num_rows was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

646
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkTable) > 0) {
Loading history...
647
            $query       = "select * from ".TABLE_PAGANTIS_CONFIG;
648
            $result      = tep_db_query($query);
649
            $response    = array();
650
            while ($resultArray = tep_db_fetch_array($result)) {
0 ignored issues
show
Bug introduced by
The function tep_db_fetch_array was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

650
            while ($resultArray = /** @scrutinizer ignore-call */ tep_db_fetch_array($result)) {
Loading history...
651
                $response[$resultArray['config']] = $resultArray['value'];
652
            }
653
        }
654
655
        return $response;
656
    }
657
658
    /**
659
     * @param $item
660
     *
661
     * @return bool
662
     */
663
    private function isPromoted($item)
664
    {
665
        $productId = explode('{', $item['id'], 1);
666
        $productId = $productId['0'];
667
668
        if ($this->extraConfig['PAGANTIS_PROMOTION'] == '') {
669
            $promotedProducts = array();
670
        } else {
671
            $promotedProducts = array_values((array)unserialize($this->extraConfig['PAGANTIS_PROMOTION']));
672
        }
673
674
        return (in_array($productId, $promotedProducts));
675
    }
676
677
    /**
678
     * @return string
679
     */
680
    private function getDescription()
681
    {
682
        $descriptionCode = "<img src=\"images/icon_info.gif\" border=\"0\" alt=\"Info\" title=\"Info\">&nbsp;<strong>Module version:</strong> $this->version<br/><br/>";
683
        $descriptionCode.= "<img src=\"images/icon_info.gif\" border=\"0\">&nbsp;<a href='https://developer.pagantis.com/' target=\"_blank\" style=\"text-decoration: underline; font-weight: bold;\">View Online Documentation</a><br/><br/>";
684
        $descriptionCode.= "<img src='images/icon_popup.gif'  border='0'>        <a href='http://pagantis.com' target='_blank' style='text-decoration: underline; font-weight: bold;'>Visit Pagantis Website</a><br/><br/><br/>";
685
686
        if (MODULE_PAYMENT_PAGANTIS_STATUS == 'True') {
0 ignored issues
show
Bug introduced by
The constant MODULE_PAYMENT_PAGANTIS_STATUS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
687
            $pagantisPromotionUrl = $this->base_url.'/admin/promotion.php';
688
            $linkDescription = "Si deseas ofrecer financiación sin intereses para alguno de tus productos ";
689
            $descriptionCode.= "<img src='images/icon_info.gif' border='0'/> $linkDescription<a href='$pagantisPromotionUrl' style='text-decoration: underline; font-weight: bold;'>haz click aquí</a>";
690
        }
691
692
        return $descriptionCode;
693
    }
694
695
    /**
696
     * @return bool
697
     */
698
    private function installSimulator()
699
    {
700
        $checkSimulator = tep_db_query("select configuration_key, configuration_value from " .TABLE_CONFIGURATION ." 
0 ignored issues
show
Bug introduced by
The function tep_db_query was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

700
        $checkSimulator = /** @scrutinizer ignore-call */ tep_db_query("select configuration_key, configuration_value from " .TABLE_CONFIGURATION ." 
Loading history...
Bug introduced by
The constant TABLE_CONFIGURATION was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
701
                                    where configuration_key like 'MODULE_HEADER_TAGS_INSTALLED'
702
                                    and configuration_value like '%ht_pagantis.php%';");
703
        if (tep_db_num_rows($checkSimulator) > 0) {
0 ignored issues
show
Bug introduced by
The function tep_db_num_rows was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

703
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkSimulator) > 0) {
Loading history...
704
            return true;
705
        }
706
707
        $query = "UPDATE " . TABLE_CONFIGURATION . " set configuration_value = concat(configuration_value, ';ht_pagantis.php')
708
                        where configuration_key like 'MODULE_HEADER_TAGS_INSTALLED'";
709
        tep_db_query($query);
710
711
        tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable Pagantis Module', 'MODULE_HEADER_TAGS_PAGANTIS_STATUS', 'True', '', '6', '1', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");
712
    }
713
714
    /**
715
     * @return bool
716
     */
717
    private function uninstallSimulator()
718
    {
719
        $checkSimulator = tep_db_query("select configuration_key, configuration_value from " .TABLE_CONFIGURATION ." 
0 ignored issues
show
Bug introduced by
The function tep_db_query was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

719
        $checkSimulator = /** @scrutinizer ignore-call */ tep_db_query("select configuration_key, configuration_value from " .TABLE_CONFIGURATION ." 
Loading history...
Bug introduced by
The constant TABLE_CONFIGURATION was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
720
                                    where configuration_key like 'MODULE_HEADER_TAGS_INSTALLED'
721
                                    and configuration_value like '%ht_pagantis.php%';");
722
        if (tep_db_num_rows($checkSimulator) == 0) {
0 ignored issues
show
Bug introduced by
The function tep_db_num_rows was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

722
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkSimulator) == 0) {
Loading history...
723
            return true;
724
        }
725
726
        $query = "UPDATE " . TABLE_CONFIGURATION . " set configuration_value = REPLACE(configuration_value, ';ht_pagantis.php', '')
727
                        where configuration_key like 'MODULE_HEADER_TAGS_INSTALLED'";
728
        tep_db_query($query);
729
730
        $query = "delete from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_HEADER_TAGS_PAGANTIS_STATUS'";
731
        tep_db_query($query);
732
    }
733
734
    /**
735
     * @param $exception
736
     */
737
    private function insertLog($exception)
738
    {
739
        if ($exception instanceof \Exception) {
740
            $logEntry= new LogEntry();
741
            $logEntryJson = $logEntry->error($exception)->toJson();
742
743
            $query = "insert into ".TABLE_PAGANTIS_LOG."(log) values ($logEntryJson)";
744
            tep_db_query($query);
0 ignored issues
show
Bug introduced by
The function tep_db_query was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

744
            /** @scrutinizer ignore-call */ 
745
            tep_db_query($query);
Loading history...
745
        }
746
    }
747
748
    /**
749
     * @return null
750
     */
751
    private function getNationalId()
752
    {
753
        global $order;
754
        if (isset($order->customer['national_id'])) {
755
            return $order->customer['national_id'];
756
        } elseif (isset($order->billing['piva'])) {
757
            return $order->billing['piva'];
758
        } else {
759
            return null;
760
        }
761
    }
762
763
    /**
764
     * @return null
765
     */
766
    private function getTaxId()
767
    {
768
        global $order;
769
        if (isset($order->customer['tax_id'])) {
770
            return $order->customer['tax_id'];
771
        } elseif (isset($order->billing['cf'])) {
772
            return $order->billing['cf'];
773
        } else {
774
            return null;
775
        }
776
    }
777
}
778