Passed
Pull Request — master (#4)
by Raúl
04:51 queued 02:34
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
7
define('TABLE_PAGANTIS_LOG', 'pagantis_log');
8
define('TABLE_PAGANTIS_CONFIG', 'pagantis_config');
9
define('TABLE_PAGANTIS_ORDERS', 'pagantis_order');
10
define('TABLE_PAGANTIS_CONCURRENCY', 'pagantis_concurrency');
11
define('MODULE_PAYMENT_PAGANTIS_TEXT_ADMIN_TITLE', 'Pagantis');
12
define('__ROOT__', dirname(dirname(__FILE__)));
13
14
class pagantis
15
{
16
    /** @var  String $is_guest */
17
    public $is_guest;
18
19
    /** @var Array $extraConfig */
20
    public $extraConfig;
21
22
    /** @var String $form_action_url */
23
    public $form_action_url;
24
25
    /** @var String $base_url */
26
    public $base_url;
27
28
    /** @var String $os_order_reference */
29
    public $os_order_reference;
30
31
    /** @var notifyController $pgNotify */
32
    public $pgNotify;
33
34
    /** @var string $langCode */
35
    public $langCode = null;
36
37
    public $defaultConfigs = array('PAGANTIS_TITLE'=>'Instant Financing',
38
                                   'PAGANTIS_SIMULATOR_DISPLAY_TYPE'=>'pgSDK.simulator.types.SIMPLE',
39
                                   'PAGANTIS_SIMULATOR_DISPLAY_SKIN'=>'pgSDK.simulator.skins.BLUE',
40
                                   'PAGANTIS_SIMULATOR_DISPLAY_POSITION'=>'hookDisplayProductButtons',
41
                                   'PAGANTIS_SIMULATOR_START_INSTALLMENTS'=>3,
42
                                   'PAGANTIS_SIMULATOR_MAX_INSTALLMENTS'=>12,
43
                                   'PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'=>'default',
44
                                   'PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION'=>'pgSDK.simulator.positions.INNER',
45
                                   'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'=>'default',
46
                                   'PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'=>'default',
47
                                   'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR_CHECKOUT'=>'default',
48
                                   'PAGANTIS_FORM_DISPLAY_TYPE'=>0,
49
                                   'PAGANTIS_DISPLAY_MIN_AMOUNT'=>1,
50
                                   'PAGANTIS_URL_OK'=>'',
51
                                   'PAGANTIS_URL_KO'=>'',
52
                                   'PAGANTIS_TITLE_EXTRA' => 'Paga hasta en 12 cómodas cuotas con Paga+Tarde. Solicitud totalmente online y sin papeleos,¡y la respuesta es inmediata!',
53
                                   'PAGANTIS_PROMOTION' => '',
54
                                   'PAGANTIS_PROMOTED_PRODUCT_CODE' => '<p>PRODUCTO PROMOCIONADO CON<img style="height: 40px; vertical-align: middle;" src="/ext/modules/payment/pagantis/img/logo_pagantis.png"/>AL 0%'
55
    );
56
57
    /**
58
     * Constructor
59
     */
60
    public function __construct()
61
    {
62
        $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...
63
        $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...
64
        $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...
65
        $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...
66
        $this->extraConfig = $this->getExtraConfig();
67
68
        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...
69
            $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...
70
        } else {
71
            $this->title = $this->extraConfig['PAGANTIS_TITLE'] .'<br/><br/><div class="buttonSet" style="display:none"></div><br/>'; // Payment module title in Catalog
72
        }
73
74
        $this->enabled = ((MODULE_PAYMENT_PAGANTIS_STATUS == 'True') ? true : false);
0 ignored issues
show
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...
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...
75
76
        $this->base_url = dirname(
77
            sprintf(
78
                "%s://%s%s%s",
79
                isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
80
                $_SERVER['SERVER_NAME'],
81
                isset($_SERVER['SERVER_PORT']) ? ":" . $_SERVER['SERVER_PORT'] : '',
82
                $_SERVER['REQUEST_URI']
83
            )
84
        );
85
86
        $this->form_action_url = $this->base_url . '/ext/modules/payment/pagantis/bypass.php';
87
88
        if (defined('MODULE_PAYMENT_PAGANTIS_LANG_CODE')) {
89
            $this->langCode = MODULE_PAYMENT_PAGANTIS_LANG_CODE;
90
        }
91
    }
92
93
    /***************
94
     *
95
     * CLASS METHODS
96
     *
97
     **************/
98
    /**
99
     * Here you can implement using payment zones (refer to standard PayPal module as reference)
100
     */
101
    public function update_status()
102
    {
103
104
    }
105
106
    /*
107
    * Here you may define client side javascript that will verify any input fields you use in the payment method
108
    * selection page. Refer to standard cc module as reference (cc.php).
109
    */
110
    public function javascript_validation()
111
    {
112
        return false;
113
    }
114
115
    /*
116
    * Llamada cuando el usuario esta en la pantalla de eleccion de tipo de pago
117
     * This function outputs the payment method title/text and if required, the input fields.
118
    *
119
    * Si hay un pedido generado previamente y no confirmado, se borra
120
    * Caso de uso:
121
    * - el usuario llega a la pantalla de confirmacion
122
    * - se genera el pedido (pero no se genera entrada en orders_status_history)
123
    * - el usuario decide realizar algun cambio en su compra antes de pasar a pagantis
124
    * - entra de nuevo en la pantalla de seleccion de tipo de pago (puede elegir otra forma de pago)
125
    * - se comprueba que no exista el pedido generado anteriormente
126
    * - se borra el pedido que se habia generado inicialmente. Ya no es valido
127
    *
128
    */
129
    public function selection()
130
    {
131
        return array('id' => $this->code, 'module' => $this->title);
132
    }
133
134
    /*
135
    * Use this function implement any checks of any conditions after payment method has been selected. You most probably
136
    *  don't need to implement anything here.
137
    */
138
    public function pre_confirmation_check()
139
    {
140
        return false;
141
    }
142
143
    /*
144
     * Implement any checks or processing on the order information before proceeding to payment confirmation. You most
145
    probably don't need to implement anything here.
146
    * Llamada cuando el usuario entra en la pantalla de confirmacion
147
    *
148
    * Se genera el pedido:
149
    * - con el estado predefinido para el modulo pagantis
150
    * - sin notificacion a cliente ni administrador
151
    * - no se borra el carrito asociado al pedido
152
    *
153
    */
154
    public function confirmation()
155
    {
156
        return false;
157
    }
158
159
    /**
160
     * Build the data and actions to process when the "Submit" button is pressed on the order-confirmation screen.
161
     * This sends the data to the payment gateway for processing.
162
     * (These are hidden fields on the checkout confirmation page)
163
     */
164
    public function process_button()
165
    {
166
        try {
167
            include_once('./ext/modules/payment/pagantis/vendor/autoload.php');
168
            global $order, $customer_id, $sendto, $billto, $cart, $languages_id, $currency, $currencies, $shipping,
169
                   $payment, $comments, $customer_default_address_id, $cartID;
170
            $global_vars = array();
171
            $global_vars['customer_id'] = serialize($customer_id);
172
            $global_vars['sendTo'] = serialize($sendto);
173
            $global_vars['billTo'] = serialize($billto);
174
            $global_vars['cart'] = serialize($cart);
175
            $global_vars['languages_id'] = serialize($languages_id);
176
            $global_vars['currency'] = serialize($currency);
177
            $global_vars['currencies'] = serialize($currencies);
178
            $global_vars['shipping'] = serialize($shipping);
179
            $global_vars['payment'] = serialize($payment);
180
            $global_vars['comments'] = serialize($comments);
181
            $global_vars['$customer_default_address_id'] = serialize($customer_default_address_id);
182
            $global_vars['cartID'] = serialize($cartID);
183
            $global_vars['sessiontoken'] = serialize($_SESSION['sessiontoken']);
184
185
            if (!isset($order)) {
186
                throw new UnknownException("Order not found");
187
            }
188
189
            $id_hash = time() . serialize($order->products) . '' . serialize($order->customer) . '' . serialize($order->delivery);
190
            $this->os_order_reference = md5($id_hash);
191
            $_SESSION['order_id'] = $this->os_order_reference;
192
193
            $userAddress = new Address();
194
            $userAddress
195
                ->setZipCode($order->billing['postcode'])
196
                ->setFullName($order->billing['firstname'] . ' ' . $order->billing['lastname'])
197
                ->setCountryCode('ES')
198
                ->setCity($order->billing['city'])
199
                ->setAddress($order->billing['street_address'])
200
                ->setFixPhone($order->customer['telephone'])
201
                ->setMobilePhone($order->customer['telephone']);
202
203
            $orderBillingAddress = $userAddress;
204
205
            $orderShippingAddress = new Address();
206
            $orderShippingAddress
207
                ->setZipCode($order->delivery['postcode'])
208
                ->setFullName($order->billing['firstname'] . ' ' . $order->billing['lastname'])
209
                ->setCountryCode('ES')
210
                ->setCity($order->delivery['city'])
211
                ->setAddress($order->delivery['street_address'])
212
                ->setFixPhone($order->customer['telephone'])
213
                ->setMobilePhone($order->customer['telephone']);
214
215
            $orderUser = new \Pagantis\OrdersApiClient\Model\Order\User();
216
            $orderUser
217
                ->setAddress($userAddress)
218
                ->setFullName($order->billing['firstname'] . ' ' . $order->billing['lastname'])
219
                ->setBillingAddress($orderBillingAddress)
220
                ->setEmail($order->customer['email_address'])
221
                ->setFixPhone($order->customer['telephone'])
222
                ->setMobilePhone($order->customer['telephone'])
223
                ->setShippingAddress($orderShippingAddress);
224
225
            $previousOrders = $this->getOrders();
226
            foreach ((array)$previousOrders as $k => $previousOrder) {
227
                $orderHistory = new \Pagantis\OrdersApiClient\Model\Order\User\OrderHistory();
228
                $orderHistory
229
                    ->setAmount(intval(100 * $previousOrder['value']))
230
                    ->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

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

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

323
                $output .= /** @scrutinizer ignore-call */ tep_draw_hidden_field("formUrl", $url) . "\n";
Loading history...
324
                $output .= tep_draw_hidden_field("cancelUrl", $cancelUrl) . "\n";
325
                return $output;
326
327
            } //TODO IFRAME
328
        } catch (\Exception $exception) {
329
            tep_redirect($cancelUrl);
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

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

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

372
            $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...
373
        }
374
        $this->installPagantisTables();
375
        return $this->_check;
376
    }
377
378
    /**
379
     * This is where you define module's configurations (displayed in admin).
380
     */
381
    public function install()
382
    {
383
        global $messageStack;
384
385
        if (defined('MODULE_PAYMENT_PAGANTIS_STATUS')) {
386
            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

386
            tep_redirect(/** @scrutinizer ignore-call */ tep_href_link(FILENAME_MODULES, 'set=payment&module=pagantis', 'NONSSL'));
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

386
            /** @scrutinizer ignore-call */ 
387
            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...
387
            return 'failed';
388
        }
389
390
        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

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

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

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

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

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

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

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

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

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

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

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

639
            while ($resultArray = /** @scrutinizer ignore-call */ tep_db_fetch_array($result)) {
Loading history...
640
                $response[$resultArray['config']] = $resultArray['value'];
641
            }
642
        }
643
644
        return $response;
645
    }
646
647
    /**
648
     * @param $item
649
     *
650
     * @return bool
651
     */
652
    private function isPromoted($item)
0 ignored issues
show
Unused Code introduced by
The parameter $item is not used and could be removed. ( Ignorable by Annotation )

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

652
    private function isPromoted(/** @scrutinizer ignore-unused */ $item)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
653
    {
654
        //HOOK WHILE PROMOTED AMOUNT IS NOT WORKING
655
        return false;
656
657
        $productId = explode('{', $item['id'], 1);
0 ignored issues
show
Unused Code introduced by
$productId = explode('{', $item['id'], 1) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
658
        $productId = $productId['0'];
659
660
        if ($this->extraConfig['PAGANTIS_PROMOTION'] == '') {
661
            $promotedProducts = array();
662
        } else {
663
            $promotedProducts = array_values((array)unserialize($this->extraConfig['PAGANTIS_PROMOTION']));
664
        }
665
666
        return (in_array($productId, $promotedProducts));
667
    }
668
669
    /**
670
     * @return string
671
     */
672
    private function getDescription()
673
    {
674
        $descriptionCode = "<img src=\"images/icon_info.gif\" border=\"0\" alt=\"Info\" title=\"Info\">&nbsp;<strong>Module version:</strong> $this->version<br/><br/>";
675
        $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/>";
676
        $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/>";
677
678
        if (MODULE_PAYMENT_PAGANTIS_STATUS == 'True' && $this->isPromoted(null)) {
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...
679
            $pagantisPromotionUrl = $this->base_url.'/admin/promotion.php';
680
            $linkDescription = "Si desea gestionar los productos promocionados pulse aquí";
681
            $descriptionCode.= "<a href='$pagantisPromotionUrl'>$linkDescription</a>";
682
        }
683
684
        return $descriptionCode;
685
    }
686
687
    /**
688
     * @return bool
689
     */
690
    private function installSimulator()
691
    {
692
        $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

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

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

708
        $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...
709
                                    where configuration_key like 'MODULE_HEADER_TAGS_INSTALLED'
710
                                    and configuration_value like '%ht_pagantis.php%';");
711
        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

711
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkSimulator) == 0) {
Loading history...
712
            return true;
713
        }
714
715
        $query = "UPDATE " . TABLE_CONFIGURATION . " set configuration_value = REPLACE(configuration_value, ';ht_pagantis.php', '')
716
                        where configuration_key like 'MODULE_HEADER_TAGS_INSTALLED'";
717
        tep_db_query($query);
718
719
        $query = "delete from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_HEADER_TAGS_PAGANTIS_STATUS'";
720
        tep_db_query($query);
721
    }
722
}
723