Passed
Pull Request — master (#4)
by
unknown
03:21 queued 22s
created

pagantis::uninstallSimulator()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

316
                $output .= /** @scrutinizer ignore-call */ tep_draw_hidden_field("formUrl", $url) . "\n";
Loading history...
317
                $output .= tep_draw_hidden_field("cancelUrl", $cancelUrl) . "\n";
318
                return $output;
319
320
            } //TODO IFRAME
321
        } catch (\Exception $exception) {
322
            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

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

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

365
            $this->_check = /** @scrutinizer ignore-call */ tep_db_num_rows($check_query);
Loading history...
366
        }
367
        $this->installPagantisTables();
368
        return $this->_check;
369
    }
370
371
    /**
372
     * This is where you define module's configurations (displayed in admin).
373
     */
374
    public function install()
375
    {
376
        global $messageStack;
377
378
        if (defined('MODULE_PAYMENT_PAGANTIS_STATUS')) {
379
            tep_redirect(tep_href_link(FILENAME_MODULES, 'set=payment&module=pagantis', 'NONSSL'));
0 ignored issues
show
Bug introduced by
The function tep_redirect was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

379
            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...
380
            return 'failed';
381
        }
382
383
        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

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

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

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

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

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

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

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

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

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

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

628
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkTable) > 0) {
Loading history...
629
            $query       = "select * from ".TABLE_PAGANTIS_CONFIG;
630
            $result      = tep_db_query($query);
631
            $response    = array();
632
            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

632
            while ($resultArray = /** @scrutinizer ignore-call */ tep_db_fetch_array($result)) {
Loading history...
633
                $response[$resultArray['config']] = $resultArray['value'];
634
            }
635
        }
636
637
        return $response;
638
    }
639
640
    /**
641
     * @param $item
642
     *
643
     * @return bool
644
     */
645
    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

645
    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...
646
    {
647
        //HOOK WHILE PROMOTED AMOUNT IS NOT WORKING
648
        return false;
649
650
        $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...
651
        $productId = $productId['0'];
652
653
        if ($this->extraConfig['PAGANTIS_PROMOTION'] == '') {
654
            $promotedProducts = array();
655
        } else {
656
            $promotedProducts = array_values((array)unserialize($this->extraConfig['PAGANTIS_PROMOTION']));
657
        }
658
659
        return (in_array($productId, $promotedProducts));
660
    }
661
662
    /**
663
     * @return string
664
     */
665
    private function getDescription()
666
    {
667
        $descriptionCode = "<img src=\"images/icon_info.gif\" border=\"0\" alt=\"Info\" title=\"Info\">&nbsp;<strong>Module version:</strong> $this->version<br/><br/>";
668
        $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/>";
669
        $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/>";
670
671
        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...
672
            $pagantisPromotionUrl = $this->base_url.'/admin/promotion.php';
673
            $linkDescription = "Si desea gestionar los productos promocionados pulse aquí";
674
            $descriptionCode.= "<a href='$pagantisPromotionUrl'>$linkDescription</a>";
675
        }
676
677
        return $descriptionCode;
678
    }
679
680
    /**
681
     * @return bool
682
     */
683
    private function installSimulator()
684
    {
685
        $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

685
        $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...
686
                                    where configuration_key like 'MODULE_HEADER_TAGS_INSTALLED'
687
                                    and configuration_value like '%ht_pagantis.php%';");
688
        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

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

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

704
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkSimulator) == 0) {
Loading history...
705
            return true;
706
        }
707
708
        $query = "UPDATE " . TABLE_CONFIGURATION . " set configuration_value = REPLACE(configuration_value, ';ht_pagantis.php', '')
709
                        where configuration_key like 'MODULE_HEADER_TAGS_INSTALLED'";
710
        tep_db_query($query);
711
712
        $query = "delete from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_HEADER_TAGS_PAGANTIS_STATUS'";
713
        tep_db_query($query);
714
    }
715
}
716