Passed
Pull Request — master (#4)
by
unknown
02:09
created

pagantis::process_button()   F

Complexity

Conditions 10
Paths 526

Size

Total Lines 165
Code Lines 134

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 0 Features 0
Metric Value
cc 10
eloc 134
c 6
b 0
f 0
nc 526
nop 0
dl 0
loc 165
rs 3.3266

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 PAGANTIS</p><img src="/ext/modules/payment/pagantis/img/sin_intereses.png"/>'
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
            $promotedAmount = 0;
232
            foreach ($order->products as $item) {
233
                $promotedProduct = $this->isPromoted($item);
234
                $product = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product();
235
                $product
236
                    ->setAmount(intval(100 * number_format(($item['final_price'] * $item['qty']), 2)))
237
                    ->setQuantity(intval($item['qty']))
238
                    ->setDescription($item['name']);
239
                if ($promotedProduct) {
240
                    $promotedAmount+=$product->getAmount();
241
                }
242
                $details->addProduct($product);
243
            }
244
245
            $orderShoppingCart = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart();
246
            $orderShoppingCart
247
                ->setDetails($details)
248
                ->setOrderReference($this->os_order_reference)
249
                ->setPromotedAmount(0)
250
                ->setTotalAmount(intval($order->info['total'] * 100))
251
                ->setPromotedAmount($promotedAmount);
252
253
            $callback_url = $this->base_url.'/ext/modules/payment/pagantis/notify.php';
254
            $checkoutProcessUrl = htmlspecialchars_decode(
255
                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

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

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

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

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

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

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

377
            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

377
            /** @scrutinizer ignore-call */ 
378
            tep_redirect(tep_href_link(FILENAME_MODULES, 'set=payment&module=pagantis', 'NONSSL'));
Loading history...
378
            return 'failed';
379
        }
380
381
        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

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

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

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

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

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

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

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

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

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

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

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

630
            while ($resultArray = /** @scrutinizer ignore-call */ tep_db_fetch_array($result)) {
Loading history...
631
                $response[$resultArray['config']] = $resultArray['value'];
632
            }
633
        }
634
635
        return $response;
636
    }
637
638
    /**
639
     * @param $item
640
     *
641
     * @return bool
642
     */
643
    private function isPromoted($item)
644
    {
645
        //HOOK WHILE PROMOTED AMOUNT IS NOT WORKING
646
        //return false;
647
648
        $productId = explode('{', $item['id'], 1);
649
        $productId = $productId['0'];
650
651
        if ($this->extraConfig['PAGANTIS_PROMOTION'] == '') {
652
            $promotedProducts = array();
653
        } else {
654
            $promotedProducts = array_values((array)unserialize($this->extraConfig['PAGANTIS_PROMOTION']));
655
        }
656
657
        return (in_array($productId, $promotedProducts));
658
    }
659
660
    /**
661
     * @return string
662
     */
663
    private function getDescription()
664
    {
665
        $descriptionCode = "<img src=\"images/icon_info.gif\" border=\"0\" alt=\"Info\" title=\"Info\">&nbsp;<strong>Module version:</strong> $this->version<br/><br/>";
666
        $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/>";
667
        $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/>";
668
        if (MODULE_PAYMENT_PAGANTIS_STATUS == 'True') {
0 ignored issues
show
Bug introduced by
The constant MODULE_PAYMENT_PAGANTIS_STATUS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
669
            $pagantisPromotionUrl = $this->base_url.'/ext/modules/payment/pagantis/promotion.php';
670
            $linkDescription = "Si desea gestionar los productos promocionados pulse aquí";
671
            $descriptionCode.= "<a href='$pagantisPromotionUrl'>$linkDescription</a>";
672
        }
673
674
        return $descriptionCode;
675
    }
676
677
    /**
678
     * @return bool
679
     */
680
    private function installSimulator()
681
    {
682
        $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

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

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

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

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