Passed
Pull Request — master (#4)
by Raúl
02:14
created

pagantis::__construct()   B

Complexity

Conditions 7
Paths 8

Size

Total Lines 30
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 0 Features 0
Metric Value
cc 7
eloc 20
c 6
b 0
f 0
nc 8
nop 0
dl 0
loc 30
rs 8.6666
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.0';
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 = $this->extraConfig['PAGANTIS_TITLE'] .'<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 = 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
            $userAddress = new Address();
195
            $userAddress
196
                ->setZipCode($order->billing['postcode'])
197
                ->setFullName($order->billing['firstname'] . ' ' . $order->billing['lastname'])
198
                ->setCountryCode('ES')
199
                ->setCity($order->billing['city'])
200
                ->setAddress($order->billing['street_address'])
201
                ->setFixPhone($order->customer['telephone'])
202
                ->setMobilePhone($order->customer['telephone']);
203
204
            $orderBillingAddress = $userAddress;
205
206
            $orderShippingAddress = new Address();
207
            $orderShippingAddress
208
                ->setZipCode($order->delivery['postcode'])
209
                ->setFullName($order->billing['firstname'] . ' ' . $order->billing['lastname'])
210
                ->setCountryCode('ES')
211
                ->setCity($order->delivery['city'])
212
                ->setAddress($order->delivery['street_address'])
213
                ->setFixPhone($order->customer['telephone'])
214
                ->setMobilePhone($order->customer['telephone']);
215
216
            $orderUser = new \Pagantis\OrdersApiClient\Model\Order\User();
217
            $orderUser
218
                ->setAddress($userAddress)
219
                ->setFullName($order->billing['firstname'] . ' ' . $order->billing['lastname'])
220
                ->setBillingAddress($orderBillingAddress)
221
                ->setEmail($order->customer['email_address'])
222
                ->setFixPhone($order->customer['telephone'])
223
                ->setMobilePhone($order->customer['telephone'])
224
                ->setShippingAddress($orderShippingAddress);
225
226
            $previousOrders = $this->getOrders();
227
            foreach ((array)$previousOrders as $k => $previousOrder) {
228
                $orderHistory = new \Pagantis\OrdersApiClient\Model\Order\User\OrderHistory();
229
                $orderHistory
230
                    ->setAmount(intval(100 * $previousOrder['value']))
231
                    ->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

231
                    ->setDate(/** @scrutinizer ignore-type */ new \DateTime($previousOrder['date_purchased']));
Loading history...
232
                $orderUser->addOrderHistory($orderHistory);
233
            }
234
235
            $details = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details();
236
            $shippingCost = number_format($order->info['shipping_cost'], 2, '.', '');
237
            $details->setShippingCost(intval(strval(100 * $shippingCost)));
238
239
            $metadataOrder = new \Pagantis\OrdersApiClient\Model\Order\Metadata();
240
            $metadata = array(
241
                '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...
242
                'pagantis' => $this->version,
243
                'php' => phpversion()
244
            );
245
            foreach ($metadata as $key => $metadatum) {
246
                $metadataOrder->addMetadata($key, $metadatum);
247
            }
248
249
            $promotedAmount = 0;
250
            foreach ($order->products as $item) {
251
                $promotedProduct = $this->isPromoted($item);
252
                $product = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product();
253
                $product
254
                    ->setAmount(intval(100 * number_format(($item['final_price'] * $item['qty']), 2)))
255
                    ->setQuantity(intval($item['qty']))
256
                    ->setDescription($item['name']);
257
                if ($promotedProduct) {
258
                    $promotedAmount+=$product->getAmount();
259
                    $promotedMessage = $product->getDescription()."-Price:".$item['final_price']."-Qty:".$product->getQuantity();
260
                    $metadataOrder->addMetadata('promotedProduct', $promotedMessage);
261
                }
262
                $details->addProduct($product);
263
            }
264
265
            $orderShoppingCart = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart();
266
            $orderShoppingCart
267
                ->setDetails($details)
268
                ->setOrderReference($this->os_order_reference)
269
                ->setTotalAmount(intval($order->info['total'] * 100))
270
                ->setPromotedAmount($promotedAmount);
271
272
            $callback_url = $this->base_url.'/ext/modules/payment/pagantis/notify.php?order_id='.$this->os_order_reference;
273
            $checkoutProcessUrl = htmlspecialchars_decode(
274
                tep_href_link(FILENAME_CHECKOUT_PROCESS, "order_id=$this->os_order_reference&from=order", 'SSL', true)
0 ignored issues
show
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

274
                /** @scrutinizer ignore-call */ 
275
                tep_href_link(FILENAME_CHECKOUT_PROCESS, "order_id=$this->os_order_reference&from=order", 'SSL', true)
Loading history...
Bug introduced by
The constant FILENAME_CHECKOUT_PROCESS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
275
            );
276
277
            $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...
278
            if ($this->extraConfig['PAGANTIS_URL_KO']!='') {
279
                $koUrl = $this->extraConfig['PAGANTIS_URL_KO'];
280
            } else {
281
                $koUrl = $cancelUrl;
282
            }
283
284
            $orderConfigurationUrls = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Urls();
285
            $orderConfigurationUrls
286
                ->setCancel($cancelUrl)
287
                ->setKo($koUrl)
288
                ->setAuthorizedNotificationCallback($callback_url)
289
                ->setRejectedNotificationCallback($callback_url)
290
                ->setOk($checkoutProcessUrl);
291
292
293
            $orderChannel = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Channel();
294
            $orderChannel
295
                ->setAssistedSale(false)
296
                ->setType(\Pagantis\OrdersApiClient\Model\Order\Configuration\Channel::ONLINE);
297
            $orderConfiguration = new \Pagantis\OrdersApiClient\Model\Order\Configuration();
298
            $orderConfiguration
299
                ->setChannel($orderChannel)
300
                ->setUrls($orderConfigurationUrls);
301
302
            $orderApiClient = new \Pagantis\OrdersApiClient\Model\Order();
303
            $orderApiClient
304
                ->setConfiguration($orderConfiguration)
305
                ->setMetadata($metadataOrder)
306
                ->setShoppingCart($orderShoppingCart)
307
                ->setUser($orderUser);
308
309
            $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...
310
            $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...
311
            $orderClient = new \Pagantis\OrdersApiClient\Client($publicKey, $secretKey);
312
            $pagantisOrder = $orderClient->createOrder($orderApiClient);
313
            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...
314
                $url = $pagantisOrder->getActionUrls()->getForm();
315
                $this->insertRow($this->os_order_reference, $pagantisOrder->getId(), serialize($global_vars));
316
            } else {
317
                throw new OrderNotFoundException();
318
            }
319
320
            if ($url == "") {
321
                throw new UnknownException(_("No ha sido posible obtener una respuesta de Pagantis"));
322
            } else {
323
                $output = "\n";
324
                $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

324
                $output .= /** @scrutinizer ignore-call */ tep_draw_hidden_field("formUrl", $url) . "\n";
Loading history...
325
                $output .= tep_draw_hidden_field("cancelUrl", $cancelUrl) . "\n";
326
                return $output;
327
328
            } //TODO IFRAME
329
        } catch (\Exception $exception) {
330
            $this->insertLog($exception);
331
            header('Location: '.$cancelUrl);
332
            exit;
333
        }
334
    }
335
336
    /**
337
     * @throws Exception
338
     */
339
    public function before_process()
340
    {
341
        include_once('./ext/modules/payment/pagantis/notifyController.php');
342
        $this->pgNotify = new notifyController();
343
        $this->pgNotify->setOscommerceOrderId($_GET['order_id']);
344
        $this->pgNotify->setOrigin(isset($_GET['from']) ? ($_GET['from']) : 'order');
345
        $this->pgNotify->processInformation();
346
    }
347
348
    /**
349
     * Post-processing activities
350
     *
351
     * @return boolean
352
     */
353
    public function after_process()
354
    {
355
        $this->pgNotify->confirmInformation();
356
    }
357
358
    /**
359
     * @return bool
360
     */
361
    public function output_error()
362
    {
363
        return false;
364
    }
365
366
    /**
367
     * @return mixed
368
     */
369
    public function check()
370
    {
371
        if (!isset($this->_check)) {
372
            $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...
373
            $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

373
            $check_query = /** @scrutinizer ignore-call */ tep_db_query($query);
Loading history...
374
            $this->_check = tep_db_num_rows($check_query);
0 ignored issues
show
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...
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

374
            $this->_check = /** @scrutinizer ignore-call */ tep_db_num_rows($check_query);
Loading history...
375
        }
376
        $this->installPagantisTables();
377
        return $this->_check;
378
    }
379
380
    /**
381
     * This is where you define module's configurations (displayed in admin).
382
     */
383
    public function install()
384
    {
385
        global $messageStack;
386
387
        if (defined('MODULE_PAYMENT_PAGANTIS_STATUS')) {
388
            tep_redirect(tep_href_link(FILENAME_MODULES, 'set=payment&module=pagantis', 'NONSSL'));
0 ignored issues
show
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

388
            tep_redirect(/** @scrutinizer ignore-call */ 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_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

388
            /** @scrutinizer ignore-call */ 
389
            tep_redirect(tep_href_link(FILENAME_MODULES, 'set=payment&module=pagantis', 'NONSSL'));
Loading history...
389
            return 'failed';
390
        }
391
392
        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

392
        /** @scrutinizer ignore-call */ 
393
        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...
393
        (
394
            configuration_title,
395
            configuration_key,
396
            configuration_value,
397
            configuration_description,
398
            configuration_group_id,
399
            sort_order,
400
            set_function,
401
            date_added) 
402
        values 
403
        (
404
            'Enable module',
405
            'MODULE_PAYMENT_PAGANTIS_STATUS',
406
            'True',
407
            '',
408
            '6',
409
            '0',
410
            'tep_cfg_select_option(array(\'True\',
411
            \'False\'),
412
            ',
413
            now()
414
        )");
415
        tep_db_query("insert into " . TABLE_CONFIGURATION . "
416
        (
417
            configuration_title,
418
            configuration_key,
419
            configuration_value,
420
            configuration_description,
421
            configuration_group_id,
422
            sort_order,
423
            date_added
424
        ) 
425
        values 
426
        (
427
            'Public Key',
428
            'MODULE_PAYMENT_PAGANTIS_PK',
429
            '',
430
            'MANDATORY. You can get in your pagantis profile',
431
            '6',
432
            '0',
433
            now()
434
        )");
435
        tep_db_query("insert into " . TABLE_CONFIGURATION . "
436
        (
437
            configuration_title,
438
            configuration_key,
439
            configuration_value,
440
            configuration_description,
441
            configuration_group_id,
442
            sort_order,
443
            date_added
444
        ) 
445
        values 
446
        (
447
            'Secret Key',
448
            'MODULE_PAYMENT_PAGANTIS_SK',
449
            '',
450
            'MANDATORY. You can get in your pagantis profile',
451
            '6',
452
            '0',
453
            now()
454
        )");
455
        tep_db_query("insert into " . TABLE_CONFIGURATION . "
456
        (
457
            configuration_title,
458
            configuration_key,
459
            configuration_value,
460
            configuration_description,
461
            configuration_group_id,
462
            sort_order,
463
            set_function,
464
            date_added
465
        ) 
466
        values 
467
        (
468
            'Include simulator',
469
            'MODULE_PAYMENT_PAGANTIS_SIMULATOR',
470
            'True',
471
            'Do you want to include Pagantis simulator',
472
            '6',
473
            '3',
474
            'tep_cfg_select_option(array(\'True\',\'False\'), ',
475
            now())"
476
        );
477
        $this->installPagantisTables();
478
479
        $this->installSimulator();
480
    }
481
482
    /**
483
     * Create the neccesary tables for the module
484
     */
485
    private function installPagantisTables()
486
    {
487
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_LOG . " ( 
488
                          id int NOT NULL AUTO_INCREMENT, 
489
                          log text NOT NULL, 
490
                          createdAt timestamp DEFAULT CURRENT_TIMESTAMP, 
491
                          UNIQUE KEY id (id))";
492
        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

492
        /** @scrutinizer ignore-call */ 
493
        tep_db_query($sql);
Loading history...
493
494
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_CONFIG . " (
495
                            id int NOT NULL AUTO_INCREMENT, 
496
                            config varchar(60) NOT NULL, 
497
                            value varchar(200) NOT NULL, 
498
                            UNIQUE KEY id(id))";
499
        tep_db_query($sql);
500
501
        // check if table has records
502
        $check_query = tep_db_query("select value from " . TABLE_PAGANTIS_CONFIG);
503
        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

503
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($check_query) === 0) {
Loading history...
504
            foreach ((array)$this->defaultConfigs as $configKey => $configValue) {
505
                $query = "INSERT INTO " . TABLE_PAGANTIS_CONFIG . "
506
                (
507
                    config,
508
                    value
509
                ) 
510
                values 
511
                (
512
                    '$configKey',
513
                    '$configValue'
514
                )";
515
                tep_db_query($query);
516
            }
517
        }
518
519
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_ORDERS . " (
520
                            id int NOT NULL AUTO_INCREMENT, 
521
                            os_order_id varchar(50), 
522
                            os_order_reference varchar(50) NOT NULL,
523
                            pagantis_order_id varchar(50) NOT NULL, 
524
                            globals text,
525
                            UNIQUE KEY id(id))";
526
        tep_db_query($sql);
527
528
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_CONCURRENCY . " (
529
                            id varchar(50) NOT NULL,
530
                            `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
531
                            UNIQUE KEY id(id))";
532
        tep_db_query($sql);
533
    }
534
535
    /**
536
     * Standard functionality to uninstall the module.
537
     */
538
    public function remove()
539
    {
540
        $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

540
        $checkTable = /** @scrutinizer ignore-call */ tep_db_query("SHOW TABLES LIKE '" . TABLE_PAGANTIS_LOG . "'");
Loading history...
541
        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

541
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkTable) > 0) {
Loading history...
542
            tep_db_query("drop table " . TABLE_PAGANTIS_LOG);
543
        }
544
545
        $checkTable = tep_db_query("SHOW TABLES LIKE '" . TABLE_PAGANTIS_CONFIG . "'");
546
        if (tep_db_num_rows($checkTable) > 0) {
547
            tep_db_query("drop table " . TABLE_PAGANTIS_CONFIG);
548
        }
549
550
        $checkTable = tep_db_query("SHOW TABLES LIKE '" . TABLE_PAGANTIS_ORDERS . "'");
551
        if (tep_db_num_rows($checkTable) > 0) {
552
            tep_db_query("drop table " . TABLE_PAGANTIS_ORDERS);
553
        }
554
555
        $checkTable = tep_db_query("SHOW TABLES LIKE '" . TABLE_PAGANTIS_CONCURRENCY . "'");
556
        if (tep_db_num_rows($checkTable) > 0) {
557
            tep_db_query("drop table " . TABLE_PAGANTIS_CONCURRENCY);
558
        }
559
560
        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...
561
562
        $query = "delete from " . TABLE_CONFIGURATION . " where configuration_key like '%_PAGANTIS_%'";
563
        tep_db_query($query);
564
565
        $this->uninstallSimulator();
566
    }
567
568
    /**
569
     * Internal list of configuration keys used for configuration of the module
570
     *
571
     * @return array
572
     */
573
    public function keys()
574
    {
575
        return array(
576
            'MODULE_PAYMENT_PAGANTIS_STATUS',
577
            'MODULE_PAYMENT_PAGANTIS_PK',
578
            'MODULE_PAYMENT_PAGANTIS_SK',
579
            'MODULE_PAYMENT_PAGANTIS_SIMULATOR'
580
        );
581
    }
582
583
    /**
584
     * @return array
585
     */
586
    private function getOrders()
587
    {
588
        $this->is_guest = 'true';
589
        if (trim($_SESSION['customer_id']) != '') {
590
            $this->is_guest = 'false';
591
            $query = sprintf(
592
                "select orders_total.value, orders.date_purchased from orders 
593
JOIN orders_status_history ON orders.orders_id=orders_status_history.orders_id 
594
JOIN orders_total ON orders.orders_id=orders_total.orders_id 
595
where orders.customers_id='%s' and orders_status_history.orders_status_id in ('2','3') 
596
and orders_total.class='ot_total'",
597
                $_SESSION['customer_id']
598
            );
599
600
            $response = array();
601
            $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

601
            $resultsSelect = /** @scrutinizer ignore-call */ tep_db_query($query);
Loading history...
602
            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

602
            while ($orderRow = /** @scrutinizer ignore-call */ tep_db_fetch_array($resultsSelect)) {
Loading history...
603
                $response[] = $orderRow;
604
            }
605
        }
606
607
        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...
608
    }
609
610
    /**
611
     * @param $orderId
612
     * @param $pagantisOrderId
613
     * @param $globalVars
614
     */
615
    private function insertRow($orderId, $pagantisOrderId, $globalVars)
616
    {
617
        $query = "select * from " . TABLE_PAGANTIS_ORDERS . " where os_order_reference='$orderId'";
618
        $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

618
        $resultsSelect = /** @scrutinizer ignore-call */ tep_db_query($query);
Loading history...
619
        $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

619
        $countResults = /** @scrutinizer ignore-call */ tep_db_num_rows($resultsSelect);
Loading history...
620
        if ($countResults == 0) {
621
            $query = "INSERT INTO " . TABLE_PAGANTIS_ORDERS . " 
622
                (os_order_reference, pagantis_order_id, globals) values ('$orderId', '$pagantisOrderId','$globalVars')";
623
        } else {
624
            $query = "UPDATE ".TABLE_PAGANTIS_ORDERS." set pagantis_order_id='$pagantisOrderId' 
625
                        where os_order_reference='$orderId'";
626
        }
627
        tep_db_query($query);
628
    }
629
630
    /**
631
     * @return array
632
     */
633
    private function getExtraConfig()
634
    {
635
        $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

635
        $checkTable = /** @scrutinizer ignore-call */ tep_db_query("SHOW TABLES LIKE '".TABLE_PAGANTIS_CONFIG."'");
Loading history...
636
        $response = array();
637
        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

637
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkTable) > 0) {
Loading history...
638
            $query       = "select * from ".TABLE_PAGANTIS_CONFIG;
639
            $result      = tep_db_query($query);
640
            $response    = array();
641
            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

641
            while ($resultArray = /** @scrutinizer ignore-call */ tep_db_fetch_array($result)) {
Loading history...
642
                $response[$resultArray['config']] = $resultArray['value'];
643
            }
644
        }
645
646
        return $response;
647
    }
648
649
    /**
650
     * @param $item
651
     *
652
     * @return bool
653
     */
654
    private function isPromoted($item)
655
    {
656
        $productId = explode('{', $item['id'], 1);
657
        $productId = $productId['0'];
658
659
        if ($this->extraConfig['PAGANTIS_PROMOTION'] == '') {
660
            $promotedProducts = array();
661
        } else {
662
            $promotedProducts = array_values((array)unserialize($this->extraConfig['PAGANTIS_PROMOTION']));
663
        }
664
665
        return (in_array($productId, $promotedProducts));
666
    }
667
668
    /**
669
     * @return string
670
     */
671
    private function getDescription()
672
    {
673
        $descriptionCode = "<img src=\"images/icon_info.gif\" border=\"0\" alt=\"Info\" title=\"Info\">&nbsp;<strong>Module version:</strong> $this->version<br/><br/>";
674
        $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/>";
675
        $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/>";
676
677
        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...
678
            $pagantisPromotionUrl = $this->base_url.'/admin/promotion.php';
679
            $linkDescription = "Si deseas ofrecer financiación sin intereses para alguno de tus productos ";
680
            $descriptionCode.= "<img src='images/icon_info.gif' border='0'/> $linkDescription<a href='$pagantisPromotionUrl' style='text-decoration: underline; font-weight: bold;'>haz click aquí</a>";
681
        }
682
683
        return $descriptionCode;
684
    }
685
686
    /**
687
     * @return bool
688
     */
689
    private function installSimulator()
690
    {
691
        $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

691
        $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...
692
                                    where configuration_key like 'MODULE_HEADER_TAGS_INSTALLED'
693
                                    and configuration_value like '%ht_pagantis.php%';");
694
        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

694
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkSimulator) > 0) {
Loading history...
695
            return true;
696
        }
697
698
        $query = "UPDATE " . TABLE_CONFIGURATION . " set configuration_value = concat(configuration_value, ';ht_pagantis.php')
699
                        where configuration_key like 'MODULE_HEADER_TAGS_INSTALLED'";
700
        tep_db_query($query);
701
702
        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())");
703
    }
704
705
    /**
706
     * @return bool
707
     */
708
    private function uninstallSimulator()
709
    {
710
        $checkSimulator = tep_db_query("select configuration_key, configuration_value from " .TABLE_CONFIGURATION ." 
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...
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

710
        $checkSimulator = /** @scrutinizer ignore-call */ tep_db_query("select configuration_key, configuration_value from " .TABLE_CONFIGURATION ." 
Loading history...
711
                                    where configuration_key like 'MODULE_HEADER_TAGS_INSTALLED'
712
                                    and configuration_value like '%ht_pagantis.php%';");
713
        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

713
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkSimulator) == 0) {
Loading history...
714
            return true;
715
        }
716
717
        $query = "UPDATE " . TABLE_CONFIGURATION . " set configuration_value = REPLACE(configuration_value, ';ht_pagantis.php', '')
718
                        where configuration_key like 'MODULE_HEADER_TAGS_INSTALLED'";
719
        tep_db_query($query);
720
721
        $query = "delete from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_HEADER_TAGS_PAGANTIS_STATUS'";
722
        tep_db_query($query);
723
    }
724
725
    /**
726
     * @param $exception
727
     */
728
    private function insertLog($exception)
729
    {
730
        if ($exception instanceof \Exception) {
731
            $logEntry= new LogEntry();
732
            $logEntryJson = $logEntry->error($exception)->toJson();
733
734
            $query = "insert into ".TABLE_PAGANTIS_LOG."(log) values ($logEntryJson)";
735
            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

735
            /** @scrutinizer ignore-call */ 
736
            tep_db_query($query);
Loading history...
736
        }
737
    }
738
}
739