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

pagantis::process_button()   C

Complexity

Conditions 8
Paths 208

Size

Total Lines 156
Code Lines 124

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 8
eloc 124
nc 208
nop 0
dl 0
loc 156
rs 6.0088
c 2
b 0
f 0

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_orders');
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('PAGANTIS_TITLE'=>'Instant Financing',
34
                                   'PAGANTIS_SIMULATOR_DISPLAY_TYPE'=>'pgSDK.simulator.types.SIMPLE',
35
                                   'PAGANTIS_SIMULATOR_DISPLAY_SKIN'=>'pgSDK.simulator.skins.BLUE',
36
                                   'PAGANTIS_SIMULATOR_DISPLAY_POSITION'=>'hookDisplayProductButtons',
37
                                   'PAGANTIS_SIMULATOR_START_INSTALLMENTS'=>3,
38
                                   'PAGANTIS_SIMULATOR_MAX_INSTALLMENTS'=>12,
39
                                   'PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'=>'default',
40
                                   'PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION'=>'pgSDK.simulator.positions.INNER',
41
                                   'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'=>'default',
42
                                   'PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'=>'default',
43
                                   'PAGANTIS_FORM_DISPLAY_TYPE'=>0,
44
                                   'PAGANTIS_DISPLAY_MIN_AMOUNT'=>1,
45
                                   'PAGANTIS_URL_OK'=>'',
46
                                   'PAGANTIS_URL_KO'=>'',
47
                                   'PAGANTIS_TITLE_EXTRA' => 'Paga hasta en 12 cómodas cuotas con Paga+Tarde. Solicitud totalmente online y sin papeleos,¡y la respuesta es inmediata!'
48
    );
49
50
    /**
51
    * Constructor
52
    */
53
    public function __construct()
54
    {
55
        $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...
56
        $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...
57
        $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...
58
59
        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...
60
            $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...
61
        } else {
62
            $this->title = MODULE_PAYMENT_PAGANTIS_TEXT_CATALOG_TITLE; // Payment module title in Catalog
63
        }
64
65
        $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...
66
67
        $this->extraConfig = $this->getExtraConfig();
68
        
69
        $this->base_url = dirname(
70
            sprintf(
71
                "%s://%s%s%s",
72
                isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
73
                $_SERVER['SERVER_NAME'],
74
                isset($_SERVER['SERVER_PORT']) ? ":".$_SERVER['SERVER_PORT'] : '',
75
                $_SERVER['REQUEST_URI']
76
            )
77
        );
78
79
        $this->form_action_url = $this->base_url . '/ext/modules/payment/pagantis/bypass.php';
80
    }
81
82
    /***************
83
     *
84
     * CLASS METHODS
85
     *
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, $payment, $comments, $customer_default_address_id, $cartID;
159
            $global_vars = array();
160
            $global_vars['customer_id'] = serialize($customer_id);
161
            $global_vars['sendTo'] = serialize($sendto);
162
            $global_vars['billTo'] = serialize($billto);
163
            $global_vars['cart'] = serialize($cart);
164
            $global_vars['languages_id'] = serialize($languages_id);
165
            $global_vars['currency'] = serialize($currency);
166
            $global_vars['currencies'] = serialize($currencies);
167
            $global_vars['shipping'] = serialize($shipping);
168
            $global_vars['payment'] = serialize($payment);
169
            $global_vars['comments'] = serialize($comments);
170
            $global_vars['$customer_default_address_id'] = serialize($customer_default_address_id);
171
            $global_vars['cartID'] = serialize($cartID);
172
            $global_vars['sessiontoken'] = serialize($_SESSION['sessiontoken']);
173
174
            if (!isset($order)) {
175
                throw new UnknownException("Order not found");
176
            }
177
178
            $id_hash = time().serialize($order->products).''.serialize($order->customer).''.serialize($order->delivery);
179
            $this->os_order_reference = md5($id_hash);
180
            $_SESSION['order_id'] = $this->os_order_reference;
181
182
            $userAddress = new Address();
183
            $userAddress
184
                ->setZipCode($order->billing['postcode'])
185
                ->setFullName($order->billing['firstname'].' '.$order->billing['lastname'])
186
                ->setCountryCode('ES')
187
                ->setCity($order->billing['city'])
188
                ->setAddress($order->billing['street_address'])
189
                ->setFixPhone($order->customer['telephone'])
190
                ->setMobilePhone($order->customer['telephone']);
191
192
            $orderBillingAddress = $userAddress;
193
194
            $orderShippingAddress = new Address();
195
            $orderShippingAddress
196
                ->setZipCode($order->delivery['postcode'])
197
                ->setFullName($order->billing['firstname'].' '.$order->billing['lastname'])
198
                ->setCountryCode('ES')
199
                ->setCity($order->delivery['city'])
200
                ->setAddress($order->delivery['street_address'])
201
                ->setFixPhone($order->customer['telephone'])
202
                ->setMobilePhone($order->customer['telephone']);
203
204
            $orderUser = new \Pagantis\OrdersApiClient\Model\Order\User();
205
            $orderUser
206
                ->setAddress($userAddress)
207
                ->setFullName($order->billing['firstname'].' '.$order->billing['lastname'])
208
                ->setBillingAddress($orderBillingAddress)
209
                ->setEmail($order->customer['email_address'])
210
                ->setFixPhone($order->customer['telephone'])
211
                ->setMobilePhone($order->customer['telephone'])
212
                ->setShippingAddress($orderShippingAddress);
213
214
            $previousOrders = $this->getOrders();
215
            foreach ((array)$previousOrders as $k => $previousOrder) {
216
                $orderHistory = new \Pagantis\OrdersApiClient\Model\Order\User\OrderHistory();
217
                $orderHistory
218
                    ->setAmount(intval(100 * $previousOrder['value']))
219
                    ->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

219
                    ->setDate(/** @scrutinizer ignore-type */ new \DateTime($previousOrder['date_purchased']))
Loading history...
220
                ;
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
                tep_href_link(FILENAME_CHECKOUT_PROCESS, "order_id=$this->os_order_reference", 'SSL', true, false)
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

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

297
                $output.= /** @scrutinizer ignore-call */ tep_draw_hidden_field("formUrl", $url) . "\n";
Loading history...
298
                $output.= tep_draw_hidden_field("cancelUrl", $cancelUrl) . "\n";
299
                return $output;
300
            } /*else {
301
                $template_fields = array(
302
                    'url'         => $url,
303
                    'checkoutUrl' => $cancelUrl
304
                );
305
                wc_get_template('iframe.php', $template_fields, '', $this->template_path); //TODO
306
            }*/ //
307
        } catch (\Exception $exception) {
308
            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

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

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

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

358
            /** @scrutinizer ignore-call */ 
359
            tep_redirect(tep_href_link(FILENAME_MODULES, 'set=payment&module=pagantis', 'NONSSL'));
Loading history...
Bug introduced by
The constant FILENAME_MODULES was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
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

358
            tep_redirect(/** @scrutinizer ignore-call */ tep_href_link(FILENAME_MODULES, 'set=payment&module=pagantis', 'NONSSL'));
Loading history...
359
            return 'failed';
360
        }
361
        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_PAYMENT_PAGANTIS_STATUS', 'True', '', '6', '0', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");
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

361
        /** @scrutinizer ignore-call */ 
362
        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_PAYMENT_PAGANTIS_STATUS', 'True', '', '6', '0', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");
Loading history...
362
        tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Public Key', 'MODULE_PAYMENT_PAGANTIS_PK', '', 'MANDATORY. You can get in your pagantis profile', '6', '0', now())");
363
        tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Secret Key', 'MODULE_PAYMENT_PAGANTIS_SK', '', 'MANDATORY. You can get in your pagantis profile', '6', '0', now())");
364
365
        $this->installPagantisTables();
366
    }
367
368
    /**
369
     * Create the neccesary tables for the module
370
     */
371
    private function installPagantisTables()
372
    {
373
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_LOG . " ( 
374
                          id int NOT NULL AUTO_INCREMENT, 
375
                          log text NOT NULL, 
376
                          createdAt timestamp DEFAULT CURRENT_TIMESTAMP, 
377
                          UNIQUE KEY id (id))";
378
        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

378
        /** @scrutinizer ignore-call */ 
379
        tep_db_query($sql);
Loading history...
379
380
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_CONFIG . " (
381
                            id int NOT NULL AUTO_INCREMENT, 
382
                            config varchar(60) NOT NULL, 
383
                            value varchar(200) NOT NULL, 
384
                            UNIQUE KEY id(id))";
385
        tep_db_query($sql);
386
        foreach ((array)$this->defaultConfigs as $configKey => $configValue) {
387
            $query = "INSERT INTO " . TABLE_PAGANTIS_CONFIG . " (config, value) values ('$configKey', '$configValue')";
388
            tep_db_query($query);
389
        }
390
391
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_ORDERS . " (
392
                            id int NOT NULL AUTO_INCREMENT, 
393
                            os_order_id varchar(50), 
394
                            os_order_reference varchar(50) NOT NULL,
395
                            pagantis_order_id varchar(50) NOT NULL, 
396
                            globals text,
397
                            UNIQUE KEY id(id))";
398
        tep_db_query($sql);
399
400
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_CONCURRENCY . " (
401
                            id int NOT NULL,
402
                            `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
403
                            UNIQUE KEY id(id))";
404
        tep_db_query($sql);
405
    }
406
407
    /*
408
     * Standard functionality to uninstall the module.
409
     */
410
    public function remove()
411
    {
412
        $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

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

413
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkTable) > 0) {
Loading history...
414
            tep_db_query("drop table " . TABLE_PAGANTIS_LOG);
415
        }
416
417
        $checkTable = tep_db_query("SHOW TABLES LIKE '".TABLE_PAGANTIS_CONFIG."'");
418
        if (tep_db_num_rows($checkTable) > 0) {
419
            tep_db_query("drop table " . TABLE_PAGANTIS_CONFIG);
420
        }
421
422
        $checkTable = tep_db_query("SHOW TABLES LIKE '".TABLE_PAGANTIS_ORDERS."'");
423
        if (tep_db_num_rows($checkTable) > 0) {
424
            tep_db_query("drop table " . TABLE_PAGANTIS_ORDERS);
425
        }
426
427
        $checkTable = tep_db_query("SHOW TABLES LIKE '".TABLE_PAGANTIS_CONCURRENCY."'");
428
        if (tep_db_num_rows($checkTable) > 0) {
429
            tep_db_query("drop table " . TABLE_PAGANTIS_CONCURRENCY);
430
        }
431
432
        $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...
433
        tep_db_query($query);
434
    }
435
436
    /**
437
    * Internal list of configuration keys used for configuration of the module
438
    *
439
    * @return array
440
    */
441
    public function keys()
442
    {
443
        return array('MODULE_PAYMENT_PAGANTIS_STATUS',
444
           'MODULE_PAYMENT_PAGANTIS_PK',
445
           'MODULE_PAYMENT_PAGANTIS_SK'
446
           );
447
    }
448
449
    /**
450
     * @return array
451
     */
452
    private function getOrders()
453
    {
454
        $this->is_guest = 'true';
455
        if (trim($_SESSION['customer_id']) != '') {
456
            $this->is_guest = 'false';
457
            $query = sprintf(
458
                "select orders_total.value, orders.date_purchased from orders 
459
JOIN orders_status_history ON orders.orders_id=orders_status_history.orders_id 
460
JOIN orders_total ON orders.orders_id=orders_total.orders_id 
461
where orders.customers_id='%s' and orders_status_history.orders_status_id in ('2','3') and orders_total.class='ot_total'",
462
                $_SESSION['customer_id']
463
            );
464
465
            $response = array();
466
            $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

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

467
            while ($orderRow = /** @scrutinizer ignore-call */ tep_db_fetch_array($resultsSelect)) {
Loading history...
468
                $response[] = $orderRow;
469
            }
470
        }
471
472
        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...
473
    }
474
475
    /**
476
     * @param $orderId
477
     * @param $pagantisOrderId
478
     * @param $globalVars
479
     */
480
    private function insertRow($orderId, $pagantisOrderId, $globalVars)
481
    {
482
        $query = "select * from ". TABLE_PAGANTIS_ORDERS ." where os_order_reference='$orderId'";
483
        $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

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

484
        $countResults = /** @scrutinizer ignore-call */ tep_db_num_rows($resultsSelect);
Loading history...
485
        if ($countResults == 0) {
486
            $query = "INSERT INTO ". TABLE_PAGANTIS_ORDERS ."(os_order_reference, pagantis_order_id, globals) values ('$orderId', '$pagantisOrderId','$globalVars')";
487
        } else {
488
            $query = "UPDATE " . TABLE_PAGANTIS_ORDERS . " set pagantis_order_id='$pagantisOrderId' where os_order_reference='$orderId'";
489
        }
490
        tep_db_query($query);
491
    }
492
493
    /**
494
     * @return array
495
     */
496
    private function getExtraConfig()
497
    {
498
        $checkTable = tep_db_query("SHOW TABLES LIKE '".TABLE_PAGANTIS."'");
0 ignored issues
show
Bug introduced by
The constant TABLE_PAGANTIS 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

498
        $checkTable = /** @scrutinizer ignore-call */ tep_db_query("SHOW TABLES LIKE '".TABLE_PAGANTIS."'");
Loading history...
499
        $response = array();
500
        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

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

503
            $resultArray = /** @scrutinizer ignore-call */ tep_db_fetch_array($result);
Loading history...
504
            $response    = array();
505
            foreach ((array)$resultArray as $key => $value) {
506
                $response[$key] = $value;
507
            }
508
        }
509
510
        return $response;
511
    }
512
}
513