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

pagantis::before_process()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
nc 1
nop 0
dl 0
loc 8
rs 10
c 2
b 0
f 0
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
                                   'PAGANTIS_ORDER_STATUS'=>'6'
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
    /**
90
    * Here you can implement using payment zones (refer to standard PayPal module as reference)
91
    */
92
    public function update_status()
93
    {
94
95
    }
96
97
    /*
98
    * Here you may define client side javascript that will verify any input fields you use in the payment method
99
    * selection page. Refer to standard cc module as reference (cc.php).
100
    */
101
    public function javascript_validation()
102
    {
103
        return false;
104
    }
105
106
    /*
107
    * Llamada cuando el usuario esta en la pantalla de eleccion de tipo de pago
108
     * This function outputs the payment method title/text and if required, the input fields.
109
    *
110
    * Si hay un pedido generado previamente y no confirmado, se borra
111
    * Caso de uso:
112
    * - el usuario llega a la pantalla de confirmacion
113
    * - se genera el pedido (pero no se genera entrada en orders_status_history)
114
    * - el usuario decide realizar algun cambio en su compra antes de pasar a pagantis
115
    * - entra de nuevo en la pantalla de seleccion de tipo de pago (puede elegir otra forma de pago)
116
    * - se comprueba que no exista el pedido generado anteriormente
117
    * - se borra el pedido que se habia generado inicialmente. Ya no es valido
118
    *
119
    */
120
    public function selection()
121
    {
122
        return array('id' => $this->code, 'module' => $this->title);
123
    }
124
125
    /*
126
    * Use this function implement any checks of any conditions after payment method has been selected. You most probably
127
    *  don't need to implement anything here.
128
    */
129
    public function pre_confirmation_check()
130
    {
131
        return false;
132
    }
133
134
    /*
135
     * Implement any checks or processing on the order information before proceeding to payment confirmation. You most
136
    probably don't need to implement anything here.
137
    * Llamada cuando el usuario entra en la pantalla de confirmacion
138
    *
139
    * Se genera el pedido:
140
    * - con el estado predefinido para el modulo pagantis
141
    * - sin notificacion a cliente ni administrador
142
    * - no se borra el carrito asociado al pedido
143
    *
144
    */
145
    public function confirmation()
146
    {
147
        return false;
148
    }
149
150
    /**
151
     * Build the data and actions to process when the "Submit" button is pressed on the order-confirmation screen.
152
     * This sends the data to the payment gateway for processing.
153
     * (These are hidden fields on the checkout confirmation page)
154
     */
155
    public function process_button()
156
    {
157
        try {
158
            include_once('./ext/modules/payment/pagantis/vendor/autoload.php');
159
            global $order, $customer_id, $sendto, $billto, $cart, $languages_id, $currency, $currencies, $shipping, $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
                ;
222
                $orderUser->addOrderHistory($orderHistory);
223
            }
224
225
            $details      = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details();
226
            $shippingCost = number_format($order->info['shipping_cost'], 2, '.', '');
227
            $details->setShippingCost(intval(strval(100 * $shippingCost)));
228
            foreach ($order->products as $item) {
229
                $product = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product();
230
                $product
231
                    ->setAmount(intval(100 * number_format(($item['final_price'] * $item['qty']), 2)))
232
                    ->setQuantity(intval($item['qty']))
233
                    ->setDescription($item['name']);
234
                $details->addProduct($product);
235
            }
236
237
            $orderShoppingCart = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart();
238
            $orderShoppingCart
239
                ->setDetails($details)
240
                ->setOrderReference($this->os_order_reference)
241
                ->setPromotedAmount(0)
242
                ->setTotalAmount(intval($order->info['total'] * 100));
243
244
            $callback_url = $this->base_url.'/ext/modules/payment/pagantis/notify.php';
245
            $checkoutProcessUrl = htmlspecialchars_decode(
246
                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

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

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

309
            /** @scrutinizer ignore-call */ 
310
            tep_redirect($cancelUrl);
Loading history...
310
            return;
311
        }
312
    }
313
314
    /**
315
     *
316
     */
317
    public function before_process()
318
    {
319
        include_once('./ext/modules/payment/pagantis/notifyController.php');
320
        $this->pgNotify = new notifyController();var_dump($_GET['from']);var_dump($_POST);die;
0 ignored issues
show
Security Debugging Code introduced by
var_dump($_GET['from']) looks like debug code. Are you sure you do not want to remove it?
Loading history...
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
321
        $this->pgNotify->setOscommerceOrderId($_GET['order_id']);
0 ignored issues
show
Unused Code introduced by
$this->pgNotify->setOsco...erId($_GET['order_id']) is not reachable.

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

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

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

    return false;
}

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

Loading history...
322
        $this->pgNotify->setOrigin(isset($_GET['from']) ? ($_GET['from']) : 'order');
323
        $this->pgNotify->setOrderStatus($this->extraConfig['PAGANTIS_ORDER_STATUS']);
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 . " 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...
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 . " where configuration_key = 'MODULE_PAYMENT_PAGANTIS_STATUS'");
Loading history...
346
            $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

346
            $this->_check = /** @scrutinizer ignore-call */ tep_db_num_rows($check_query);
Loading history...
347
        }
348
        $this->installPagantisTables();
349
        return $this->_check;
350
    }
351
352
    /*
353
     * This is where you define module's configurations (displayed in admin).
354
     */
355
    public function install()
356
    {
357
        global $messageStack;
358
359
        if (defined('MODULE_PAYMENT_PAGANTIS_STATUS')) {
360
            tep_redirect(tep_href_link(FILENAME_MODULES, 'set=payment&module=pagantis', 'NONSSL'));
0 ignored issues
show
Bug introduced by
The function tep_href_link was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

363
        /** @scrutinizer ignore-call */ 
364
        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...
364
        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())");
365
        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())");
366
367
        //tep_db_query("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name, public_flag, downloads_flag) values (6, 1, 'Pagantis [Transactions]', 0, 0)");
368
        $this->installPagantisTables();
369
    }
370
371
    /**
372
     * Create the neccesary tables for the module
373
     */
374
    private function installPagantisTables()
375
    {
376
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_LOG . " ( 
377
                          id int NOT NULL AUTO_INCREMENT, 
378
                          log text NOT NULL, 
379
                          createdAt timestamp DEFAULT CURRENT_TIMESTAMP, 
380
                          UNIQUE KEY id (id))";
381
        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

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

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

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

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

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

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

487
        $countResults = /** @scrutinizer ignore-call */ tep_db_num_rows($resultsSelect);
Loading history...
488
        if ($countResults == 0) {
489
            $query = "INSERT INTO ". TABLE_PAGANTIS_ORDERS ."(os_order_reference, PAGANTIS_order_id, globals) values ('$this->os_order_reference', '$pagantisOrderId','$globalVars')";
490
        } else {
491
            $query = "UPDATE " . TABLE_PAGANTIS_ORDERS . " set PAGANTIS_order_id='$pagantisOrderId' where os_order_reference='$orderId'";
492
        }
493
        tep_db_query($query);
494
    }
495
496
    /**
497
     * @return array
498
     */
499
    private function getExtraConfig()
500
    {
501
        $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

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

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

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