Passed
Pull Request — master (#4)
by Raúl
03:43
created

pagantis::process_button()   C

Complexity

Conditions 8
Paths 208

Size

Total Lines 158
Code Lines 130

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 8
eloc 130
c 4
b 0
f 0
nc 208
nop 0
dl 0
loc 158
rs 6.0088

How to fix   Long Method   

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

220
                    ->setDate(/** @scrutinizer ignore-type */ new \DateTime($previousOrder['date_purchased']));
Loading history...
221
                $orderUser->addOrderHistory($orderHistory);
222
            }
223
224
            $details = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details();
225
            $shippingCost = number_format($order->info['shipping_cost'], 2, '.', '');
226
            $details->setShippingCost(intval(strval(100 * $shippingCost)));
227
            foreach ($order->products as $item) {
228
                $product = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product();
229
                $product
230
                    ->setAmount(intval(100 * number_format(($item['final_price'] * $item['qty']), 2)))
231
                    ->setQuantity(intval($item['qty']))
232
                    ->setDescription($item['name']);
233
                $details->addProduct($product);
234
            }
235
236
            $orderShoppingCart = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart();
237
            $orderShoppingCart
238
                ->setDetails($details)
239
                ->setOrderReference($this->os_order_reference)
240
                ->setPromotedAmount(0)
241
                ->setTotalAmount(intval($order->info['total'] * 100));
242
243
            $callback_url = $this->base_url . '/ext/modules/payment/pagantis/notify.php';
244
            $checkoutProcessUrl = htmlspecialchars_decode
245
            (
246
                tep_href_link(
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

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

304
                $output .= /** @scrutinizer ignore-call */ tep_draw_hidden_field("formUrl", $url) . "\n";
Loading history...
305
                $output .= tep_draw_hidden_field("cancelUrl", $cancelUrl) . "\n";
306
                return $output;
307
308
            } //TODO IFRAME
309
        } catch (\Exception $exception) {
310
            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

310
            /** @scrutinizer ignore-call */ 
311
            tep_redirect($cancelUrl);
Loading history...
311
            return;
312
        }
313
    }
314
315
    /**
316
     *
317
     */
318
    public function before_process()
319
    {
320
        include_once('./ext/modules/payment/pagantis/notifyController.php');
321
        $this->pgNotify = new notifyController();
322
        $this->pgNotify->setOscommerceOrderId($_GET['order_id']);
323
        $this->pgNotify->setOrigin(isset($_GET['from']) ? ($_GET['from']) : 'order');
324
        $this->pgNotify->processInformation();
325
    }
326
327
    /**
328
     * Post-processing activities
329
     *
330
     * @return boolean
331
     */
332
    public function after_process()
333
    {
334
        $this->pgNotify->confirmInformation();
335
    }
336
337
    public function output_error()
338
    {
339
        return false;
340
    }
341
342
    public function check()
343
    {
344
        if (!isset($this->_check)) {
345
            $check_query = tep_db_query("select 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

345
            $check_query = /** @scrutinizer ignore-call */ tep_db_query("select configuration_value from " . TABLE_CONFIGURATION . " 
Loading history...
346
                                         where configuration_key = 'MODULE_PAYMENT_PAGANTIS_STATUS'");
347
            $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

347
            $this->_check = /** @scrutinizer ignore-call */ tep_db_num_rows($check_query);
Loading history...
348
        }
349
        $this->installPagantisTables();
350
        return $this->_check;
351
    }
352
353
    /*
354
     * This is where you define module's configurations (displayed in admin).
355
     */
356
    public function install()
357
    {
358
        global $messageStack;
359
360
        if (defined('MODULE_PAYMENT_PAGANTIS_STATUS')) {
361
            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_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

361
            /** @scrutinizer ignore-call */ 
362
            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

361
            tep_redirect(/** @scrutinizer ignore-call */ tep_href_link(FILENAME_MODULES, 'set=payment&module=pagantis', 'NONSSL'));
Loading history...
362
            return 'failed';
363
        }
364
        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

364
        /** @scrutinizer ignore-call */ 
365
        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...
365
        (
366
            configuration_title,
367
            configuration_key,
368
            configuration_value,
369
            configuration_description,
370
            configuration_group_id,
371
            sort_order,
372
            set_function,
373
            date_added) 
374
        values 
375
        (
376
            'Enable Pagantis module',
377
            'MODULE_PAYMENT_PAGANTIS_STATUS',
378
            'True',
379
            '',
380
            '6',
381
            '0',
382
            'tep_cfg_select_option(array(\'True\',
383
            \'False\'),
384
            ',
385
            now()
386
        )");
387
        tep_db_query("insert into " . TABLE_CONFIGURATION . "
388
        (
389
            configuration_title,
390
            configuration_key,
391
            configuration_value,
392
            configuration_description,
393
            configuration_group_id,
394
            sort_order,
395
            date_added
396
        ) 
397
        values 
398
        (
399
            'Public Key',
400
            'MODULE_PAYMENT_PAGANTIS_PK',
401
            '',
402
            'MANDATORY. You can get in your pagantis profile',
403
            '6',
404
            '0',
405
            now()
406
        )");
407
        tep_db_query("insert into " . TABLE_CONFIGURATION . "
408
        (
409
            configuration_title,
410
            configuration_key,
411
            configuration_value,
412
            configuration_description,
413
            configuration_group_id,
414
            sort_order,
415
            date_added
416
        ) 
417
        values 
418
        (
419
            'Secret Key',
420
            'MODULE_PAYMENT_PAGANTIS_SK',
421
            '',
422
            'MANDATORY. You can get in your pagantis profile',
423
            '6',
424
            '0',
425
            now()
426
        )");
427
428
        $this->installPagantisTables();
429
430
        $this->installSimulator();
431
    }
432
433
    /**
434
     * Create the neccesary tables for the module
435
     */
436
    private function installPagantisTables()
437
    {
438
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_LOG . " ( 
439
                          id int NOT NULL AUTO_INCREMENT, 
440
                          log text NOT NULL, 
441
                          createdAt timestamp DEFAULT CURRENT_TIMESTAMP, 
442
                          UNIQUE KEY id (id))";
443
        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

443
        /** @scrutinizer ignore-call */ 
444
        tep_db_query($sql);
Loading history...
444
445
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_CONFIG . " (
446
                            id int NOT NULL AUTO_INCREMENT, 
447
                            config varchar(60) NOT NULL, 
448
                            value varchar(200) NOT NULL, 
449
                            UNIQUE KEY id(id))";
450
        tep_db_query($sql);
451
452
        // check if table has records
453
        $check_query = tep_db_query("select value from " . TABLE_PAGANTIS_CONFIG);
454
        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

454
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($check_query) === 0) {
Loading history...
455
            foreach ((array)$this->defaultConfigs as $configKey => $configValue) {
456
                $query = "INSERT INTO " . TABLE_PAGANTIS_CONFIG . "
457
                (
458
                    config,
459
                    value
460
                ) 
461
                values 
462
                (
463
                    '$configKey',
464
                    '$configValue'
465
                )";
466
                tep_db_query($query);
467
            }
468
        }
469
470
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_ORDERS . " (
471
                            id int NOT NULL AUTO_INCREMENT, 
472
                            os_order_id varchar(50), 
473
                            os_order_reference varchar(50) NOT NULL,
474
                            pagantis_order_id varchar(50) NOT NULL, 
475
                            globals text,
476
                            UNIQUE KEY id(id))";
477
        tep_db_query($sql);
478
479
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_CONCURRENCY . " (
480
                            id varchar(50) NOT NULL,
481
                            `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
482
                            UNIQUE KEY id(id))";
483
        tep_db_query($sql);
484
    }
485
486
    /*
487
     * Standard functionality to uninstall the module.
488
     */
489
    public function remove()
490
    {
491
        $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

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

492
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkTable) > 0) {
Loading history...
493
            tep_db_query("drop table " . TABLE_PAGANTIS_LOG);
494
        }
495
496
        $checkTable = tep_db_query("SHOW TABLES LIKE '" . TABLE_PAGANTIS_CONFIG . "'");
497
        if (tep_db_num_rows($checkTable) > 0) {
498
            tep_db_query("drop table " . TABLE_PAGANTIS_CONFIG);
499
        }
500
501
        $checkTable = tep_db_query("SHOW TABLES LIKE '" . TABLE_PAGANTIS_ORDERS . "'");
502
        if (tep_db_num_rows($checkTable) > 0) {
503
            tep_db_query("drop table " . TABLE_PAGANTIS_ORDERS);
504
        }
505
506
        $checkTable = tep_db_query("SHOW TABLES LIKE '" . TABLE_PAGANTIS_CONCURRENCY . "'");
507
        if (tep_db_num_rows($checkTable) > 0) {
508
            tep_db_query("drop table " . TABLE_PAGANTIS_CONCURRENCY);
509
        }
510
511
        $query = "delete from " . TABLE_ORDERS_STATUS . " where orders_status_id='6'";
0 ignored issues
show
Bug introduced by
The constant TABLE_ORDERS_STATUS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
512
        tep_db_query($query);
513
514
        $query = "delete from " . TABLE_CONFIGURATION . " where configuration_key like '%_PAGANTIS_%'";
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...
515
        tep_db_query($query);
516
517
        $this->uninstallSimulator();
518
    }
519
520
    /**
521
     * Internal list of configuration keys used for configuration of the module
522
     *
523
     * @return array
524
     */
525
    public function keys()
526
    {
527
        return array('MODULE_PAYMENT_PAGANTIS_STATUS',
528
            'MODULE_PAYMENT_PAGANTIS_PK',
529
            'MODULE_PAYMENT_PAGANTIS_SK'
530
        );
531
    }
532
533
    /**
534
     * @return array
535
     */
536
    private function getOrders()
537
    {
538
        $this->is_guest = 'true';
539
        if (trim($_SESSION['customer_id']) != '') {
540
            $this->is_guest = 'false';
541
            $query = sprintf(
542
                "select orders_total.value, orders.date_purchased from orders 
543
JOIN orders_status_history ON orders.orders_id=orders_status_history.orders_id 
544
JOIN orders_total ON orders.orders_id=orders_total.orders_id 
545
where orders.customers_id='%s' and orders_status_history.orders_status_id in ('2','3') 
546
and orders_total.class='ot_total'",
547
                $_SESSION['customer_id']
548
            );
549
550
            $response = array();
551
            $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

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

552
            while ($orderRow = /** @scrutinizer ignore-call */ tep_db_fetch_array($resultsSelect)) {
Loading history...
553
                $response[] = $orderRow;
554
            }
555
        }
556
557
        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...
558
    }
559
560
    /**
561
     * @param $orderId
562
     * @param $pagantisOrderId
563
     * @param $globalVars
564
     */
565
    private function insertRow($orderId, $pagantisOrderId, $globalVars)
566
    {
567
        $query = "select * from " . TABLE_PAGANTIS_ORDERS . " where os_order_reference='$orderId'";
568
        $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

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

569
        $countResults = /** @scrutinizer ignore-call */ tep_db_num_rows($resultsSelect);
Loading history...
570
        if ($countResults == 0) {
571
            $query = "INSERT INTO " . TABLE_PAGANTIS_ORDERS . " 
572
                (os_order_reference, pagantis_order_id, globals) values ('$orderId', '$pagantisOrderId','$globalVars')";
573
        } else {
574
            $query = "UPDATE " . TABLE_PAGANTIS_ORDERS . " set pagantis_order_id='$pagantisOrderId' 
575
                        where os_order_reference='$orderId'";
576
        }
577
        tep_db_query($query);
578
    }
579
580
    /**
581
     * @return array
582
     */
583
    private function getExtraConfig()
584
    {
585
        $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

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

587
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkTable) > 0) {
Loading history...
588
            $query = "select * from " . TABLE_PAGANTIS_CONFIG;
589
            $result = tep_db_query($query);
590
            $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

590
            $resultArray = /** @scrutinizer ignore-call */ tep_db_fetch_array($result);
Loading history...
591
            $response = array();
592
            foreach ((array)$resultArray as $key => $value) {
593
                $response[$key] = $value;
594
            }
595
        }
596
597
        return $response;
598
    }
599
600
    private function installSimulator()
601
    {
602
        $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

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

605
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkSimulator) > 0) {
Loading history...
606
            return true;
607
        }
608
609
        $query = "UPDATE " . TABLE_CONFIGURATION . " set configuration_value = concat(configuration_value, ';ht_pagantis.php')
610
                        where configuration_key like 'MODULE_HEADER_TAGS_INSTALLED'";
611
        tep_db_query($query);
612
613
        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())");
614
    }
615
616
    private function uninstallSimulator()
617
    {
618
        $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

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

621
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkSimulator) == 0) {
Loading history...
622
            return true;
623
        }
624
625
        $query = "UPDATE " . TABLE_CONFIGURATION . " set configuration_value = REPLACE(configuration_value, ';ht_pagantis.php', '')
626
                        where configuration_key like 'MODULE_HEADER_TAGS_INSTALLED'";
627
        tep_db_query($query);
628
629
        $query = "delete from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_HEADER_TAGS_PAGANTIS_STATUS'";
630
        tep_db_query($query);
631
    }
632
}