Passed
Pull Request — master (#4)
by Raúl
02:06
created

pagantis::getOrders()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 40
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 20
nc 2
nop 0
dl 0
loc 40
rs 9.6
c 0
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', 'pagantis');
8
define('TABLE_PAGANTIS_LOG', 'pagantis_log');
9
define('TABLE_PAGANTIS_CONFIG', 'pagantis_config');
10
define('TABLE_PAGANTIS_ORDERS', 'pagantis_orders');
11
define('TABLE_PAGANTIS_CONCURRENCY', 'pagantis_concurrency');
12
define('__ROOT__', dirname(dirname(__FILE__)));
13
14
class pagantis
15
{
16
    /** @var  String $is_guest */
17
    public $is_guest;
18
19
    /** @var Array $extraConfig */
20
    public $extraConfig;
21
22
    /** @var String $form_action_url */
23
    public $form_action_url;
24
25
    /** @var String $base_url */
26
    public $base_url;
27
28
    /** @var String $order_id */
29
    public $order_id;
30
31
    public $defaultConfigs = array('PMT_TITLE'=>'Instant Financing',
32
                                   'PMT_SIMULATOR_DISPLAY_TYPE'=>'pmtSDK.simulator.types.SIMPLE',
33
                                   'PMT_SIMULATOR_DISPLAY_SKIN'=>'pmtSDK.simulator.skins.BLUE',
34
                                   'PMT_SIMULATOR_DISPLAY_POSITION'=>'hookDisplayProductButtons',
35
                                   'PMT_SIMULATOR_START_INSTALLMENTS'=>3,
36
                                   'PMT_SIMULATOR_MAX_INSTALLMENTS'=>12,
37
                                   'PMT_SIMULATOR_CSS_POSITION_SELECTOR'=>'default',
38
                                   'PMT_SIMULATOR_DISPLAY_CSS_POSITION'=>'pmtSDK.simulator.positions.INNER',
39
                                   'PMT_SIMULATOR_CSS_PRICE_SELECTOR'=>'default',
40
                                   'PMT_SIMULATOR_CSS_QUANTITY_SELECTOR'=>'default',
41
                                   'PMT_FORM_DISPLAY_TYPE'=>0,
42
                                   'PMT_DISPLAY_MIN_AMOUNT'=>1,
43
                                   'PMT_URL_OK'=>'',
44
                                   'PMT_URL_KO'=>'',
45
                                   'PMT_TITLE_EXTRA' => 'Paga hasta en 12 cómodas cuotas con Paga+Tarde. Solicitud totalmente 
46
                            online y sin papeleos,¡y la respuesta es inmediata!'
47
    );
48
49
    /**
50
    * Constructor
51
    */
52
    public function __construct()
53
    {
54
        global $order;
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
58
        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...
59
            $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...
60
        } else {
61
            $this->title = MODULE_PAYMENT_PAGANTIS_TEXT_CATALOG_TITLE; // Payment module title in Catalog
62
        }
63
64
        $this->enabled = ((MODULE_PAYMENT_PAGANTIS_STATUS == 'True') ? true : false);
0 ignored issues
show
Bug introduced by
The constant MODULE_PAYMENT_PAGANTIS_STATUS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug Best Practice introduced by
The property enabled does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
65
66
        $this->getExtraConfig();
67
68
        if ((int)MODULE_PAYMENT_PAGANTIS_ORDER_STATUS_ID > 0) {
0 ignored issues
show
Bug introduced by
The constant MODULE_PAYMENT_PAGANTIS_ORDER_STATUS_ID was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
69
            $this->order_status = MODULE_PAYMENT_PAGANTIS_ORDER_STATUS_ID;
0 ignored issues
show
Bug Best Practice introduced by
The property order_status does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
70
        }
71
72
        if (strpos($_SERVER[REQUEST_URI], "checkout_confirmation.php")!==false && $_SESSION['order_id']) {
73
            if ($pmtOrderId = $this->getPmtOrderId($_SESSION['order_id'])) {
74
                $this->form_action_url = "https://form.pagamastarde.com/orders/$pmtOrderId";
75
            }
76
        }
77
        /*if (is_object($order)) {
78
            $this->update_status();
79
        }*/
80
        
81
        $this->base_url = dirname(
82
            sprintf(
83
                "%s://%s%s%s",
84
                isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
85
                $_SERVER['SERVER_NAME'],
86
                isset($_SERVER['SERVER_PORT']) ? ":".$_SERVER['SERVER_PORT'] : '',
87
                $_SERVER['REQUEST_URI']
88
            )
89
        );
90
        $this->form_action_url = $this->base_url . '/ext/modules/payment/pagantis/bypass.php';
91
    }
92
93
    /***************
94
     *
95
     * CLASS METHODS
96
     *
97
     **************/
98
99
    /**
100
    * Here you can implement using payment zones (refer to standard PayPal module as reference)
101
    */
102
    public function update_status()
103
    {
104
        global $order, $db;
105
106
        if (strpos($_SERVER[REQUEST_URI], "checkout_process.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...
107
            if ($_POST) {
108
                die('aqui hemos llegado por notificación');
0 ignored issues
show
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...
109
            } else {
110
                echo "pasamos de largo pq es un GET";
111
            }
112
        }
113
114
        if ($this->enabled && (int)MODULE_PAYMENT_PAGANTIS_ZONE > 0 && isset($order->billing['country']['id'])) {
0 ignored issues
show
Bug introduced by
The constant MODULE_PAYMENT_PAGANTIS_ZONE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
115
            $check_flag = false;
116
            $check_query = tep_db_query("select zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id = '" . MODULE_PAYMENT_PAGANTIS_ZONE . "' and zone_country_id = '" . (int)$order->billing['country']['id'] . "' order by zone_id");
0 ignored issues
show
Bug introduced by
The constant TABLE_ZONES_TO_GEO_ZONES 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

116
            $check_query = /** @scrutinizer ignore-call */ tep_db_query("select zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id = '" . MODULE_PAYMENT_PAGANTIS_ZONE . "' and zone_country_id = '" . (int)$order->billing['country']['id'] . "' order by zone_id");
Loading history...
117
            while ($check = tep_db_fetch_array($check_query)) {
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

117
            while ($check = /** @scrutinizer ignore-call */ tep_db_fetch_array($check_query)) {
Loading history...
118
                if ($check['zone_id'] < 1) {
119
                    $check_flag = true;
120
                    break;
121
                } elseif ($check['zone_id'] == $order->billing['zone_id']) {
122
                    $check_flag = true;
123
                    break;
124
                }
125
            }
126
127
            if ($check_flag == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
128
                $this->enabled = 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...
129
            }
130
        }
131
    }
132
133
    /*
134
    * Here you may define client side javascript that will verify any input fields you use in the payment method
135
    * selection page. Refer to standard cc module as reference (cc.php).
136
    */
137
    public function javascript_validation()
138
    {
139
        return false;
140
    }
141
142
    /*
143
    * Llamada cuando el usuario esta en la pantalla de eleccion de tipo de pago
144
     * This function outputs the payment method title/text and if required, the input fields.
145
    *
146
    * Si hay un pedido generado previamente y no confirmado, se borra
147
    * Caso de uso:
148
    * - el usuario llega a la pantalla de confirmacion
149
    * - se genera el pedido (pero no se genera entrada en orders_status_history)
150
    * - el usuario decide realizar algun cambio en su compra antes de pasar a pagantis
151
    * - entra de nuevo en la pantalla de seleccion de tipo de pago (puede elegir otra forma de pago)
152
    * - se comprueba que no exista el pedido generado anteriormente
153
    * - se borra el pedido que se habia generado inicialmente. Ya no es valido
154
    *
155
    */
156
    public function selection()
157
    {
158
        return array('id' => $this->code, 'module' => $this->title);
159
    }
160
161
    /*
162
    * Use this function implement any checks of any conditions after payment method has been selected. You most probably
163
    *  don't need to implement anything here.
164
    */
165
    public function pre_confirmation_check()
166
    {
167
        return false;
168
    }
169
170
    /*
171
     * Implement any checks or processing on the order information before proceeding to payment confirmation. You most
172
    probably don't need to implement anything here.
173
    * Llamada cuando el usuario entra en la pantalla de confirmacion
174
    *
175
    * Se genera el pedido:
176
    * - con el estado predefinido para el modulo pagantis
177
    * - sin notificacion a cliente ni administrador
178
    * - no se borra el carrito asociado al pedido
179
    *
180
    */
181
    public function confirmation()
182
    {
183
        return false;
184
    }
185
186
    /**
187
     * Build the data and actions to process when the "Submit" button is pressed on the order-confirmation screen.
188
     * This sends the data to the payment gateway for processing.
189
     * (These are hidden fields on the checkout confirmation page)
190
     */
191
    public function process_button()
192
    {
193
        try {
194
            include_once('./ext/modules/payment/pagantis/vendor/autoload.php');
195
            global $order, $customer_id, $sendto, $billto, $cart, $languages_id, $currency, $currencies, $shipping, $payment, $comments, $customer_default_address_id, $cartID;
196
            $global_vars = array();
197
            $global_vars['customer_id'] = serialize($customer_id);
198
            $global_vars['sendTo'] = serialize($sendto);
199
            $global_vars['billTo'] = serialize($billto);
200
            $global_vars['cart'] = serialize($cart);
201
            $global_vars['languages_id'] = serialize($languages_id);
202
            $global_vars['currency'] = serialize($currency);
203
            $global_vars['currencies'] = serialize($currencies);
204
            $global_vars['shipping'] = serialize($shipping);
205
            $global_vars['payment'] = serialize($payment);
206
            $global_vars['comments'] = serialize($comments);
207
            $global_vars['$customer_default_address_id'] = serialize($customer_default_address_id);
208
            $global_vars['cartId'] = serialize($cartID);
209
            if (!isset($order)) {
210
                throw new UnknownException("Order not found");
211
            }
212
213
            $id_hash = time().serialize($order->products).''.serialize($order->customer).''.serialize($order->delivery);
214
            $this->order_id = md5($id_hash);
215
            $_SESSION['order_id'] = $this->order_id;
216
            $sql = sprintf("insert into " . TABLE_PAGANTIS . " (order_id) values ('%s')", $this->order_id);
217
            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

217
            /** @scrutinizer ignore-call */ 
218
            tep_db_query($sql);
Loading history...
218
219
            $userAddress = new Address();
220
            $userAddress
221
                ->setZipCode($order->billing['postcode'])
222
                ->setFullName($order->billing['firstname'].' '.$order->billing['lastname'])
223
                ->setCountryCode('ES')
224
                ->setCity($order->billing['city'])
225
                ->setAddress($order->billing['street_address'])
226
                ->setFixPhone($order->customer['telephone'])
227
                ->setMobilePhone($order->customer['telephone']);
228
229
            $orderBillingAddress = $userAddress;
230
231
            $orderShippingAddress = new Address();
232
            $orderShippingAddress
233
                ->setZipCode($order->delivery['postcode'])
234
                ->setFullName($order->billing['firstname'].' '.$order->billing['lastname'])
235
                ->setCountryCode('ES')
236
                ->setCity($order->delivery['city'])
237
                ->setAddress($order->delivery['street_address'])
238
                ->setFixPhone($order->customer['telephone'])
239
                ->setMobilePhone($order->customer['telephone']);
240
241
            $orderUser = new \Pagantis\OrdersApiClient\Model\Order\User();
242
            $orderUser
243
                ->setAddress($userAddress)
244
                ->setFullName($order->billing['firstname'].' '.$order->billing['lastname'])
245
                ->setBillingAddress($orderBillingAddress)
246
                ->setEmail($order->customer['email_address'])
247
                ->setFixPhone($order->customer['telephone'])
248
                ->setMobilePhone($order->customer['telephone'])
249
                ->setShippingAddress($orderShippingAddress);
250
251
            $previousOrders = $this->getOrders();
252
            foreach ((array)$previousOrders as $previousOrder) {
253
                $orderHistory = new \Pagantis\OrdersApiClient\Model\Order\User\OrderHistory();
254
                $orderElement = wc_get_order($previousOrder);
0 ignored issues
show
Bug introduced by
The function wc_get_order 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

254
                $orderElement = /** @scrutinizer ignore-call */ wc_get_order($previousOrder);
Loading history...
255
                $orderCreated = $orderElement->get_date_created();
256
                $orderHistory
257
                    ->setAmount(intval(100 * $orderElement->get_total()))
258
                    ->setDate(new \DateTime($orderCreated->date('Y-m-d H:i:s')))
0 ignored issues
show
Bug introduced by
new DateTime($orderCreated->date('Y-m-d H:i:s')) 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

258
                    ->setDate(/** @scrutinizer ignore-type */ new \DateTime($orderCreated->date('Y-m-d H:i:s')))
Loading history...
259
                ;
260
                $orderUser->addOrderHistory($orderHistory);
261
            }
262
263
            $details      = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details();
264
            $shippingCost = number_format($order->info['shipping_cost'], 2, '.', '');
265
            $details->setShippingCost(intval(strval(100 * $shippingCost)));
266
            foreach ($order->products as $item) {
267
                $product = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product();
268
                $product
269
                    ->setAmount(intval(100 * number_format(($item['final_price'] * $item['qty']), 2)))
270
                    ->setQuantity(intval($item['qty']))
271
                    ->setDescription($item['name']);
272
                $details->addProduct($product);
273
            }
274
275
            $orderShoppingCart = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart();
276
            $orderShoppingCart
277
                ->setDetails($details)
278
                ->setOrderReference($this->order_id)
279
                ->setPromotedAmount(0)
280
                ->setTotalAmount(intval($order->info['total'] * 100));
281
282
            $callback_url = $this->base_url.'/ext/modules/payment/pagantis/notify.php';
283
            $checkoutProcessUrl = htmlspecialchars_decode(
284
                tep_href_link(FILENAME_CHECKOUT_PROCESS, "order_id=$this->order_id", 'SSL', true, false)
0 ignored issues
show
Bug introduced by
The constant FILENAME_CHECKOUT_PROCESS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The function tep_href_link was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

284
                /** @scrutinizer ignore-call */ 
285
                tep_href_link(FILENAME_CHECKOUT_PROCESS, "order_id=$this->order_id", 'SSL', true, false)
Loading history...
285
            );
286
            $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...
287
            $orderConfigurationUrls = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Urls();
288
            $orderConfigurationUrls
289
                ->setCancel($cancelUrl)
290
                ->setKo($checkoutProcessUrl)
291
                ->setAuthorizedNotificationCallback($callback_url)
292
                ->setRejectedNotificationCallback($callback_url)
293
                ->setOk($checkoutProcessUrl);
294
295
296
            $orderChannel = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Channel();
297
            $orderChannel
298
                ->setAssistedSale(false)
299
                ->setType(\Pagantis\OrdersApiClient\Model\Order\Configuration\Channel::ONLINE);
300
            $orderConfiguration = new \Pagantis\OrdersApiClient\Model\Order\Configuration();
301
            $orderConfiguration
302
                ->setChannel($orderChannel)
303
                ->setUrls($orderConfigurationUrls);
304
305
            $metadataOrder = new \Pagantis\OrdersApiClient\Model\Order\Metadata();
306
            $metadata      = array(
307
                '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...
308
                'pagantis'   => $this->version,
309
                'php'        => phpversion()
310
            );
311
            foreach ($metadata as $key => $metadatum) {
312
                $metadataOrder->addMetadata($key, $metadatum);
313
            }
314
            $orderApiClient = new \Pagantis\OrdersApiClient\Model\Order();
315
            $orderApiClient
316
                ->setConfiguration($orderConfiguration)
317
                ->setMetadata($metadataOrder)
318
                ->setShoppingCart($orderShoppingCart)
319
                ->setUser($orderUser);
320
321
            $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...
322
            $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...
323
            $orderClient   = new \Pagantis\OrdersApiClient\Client($publicKey, $secretKey);
324
            $pagantisOrder = $orderClient->createOrder($orderApiClient);
325
            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...
326
                $url = $pagantisOrder->getActionUrls()->getForm();
0 ignored issues
show
Unused Code introduced by
The assignment to $url is dead and can be removed.
Loading history...
327
                $this->insertRow($this->order_id, serialize($global_vars));
328
                die($this->order_id);
0 ignored issues
show
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...
329
            } else {
330
                throw new OrderNotFoundException();
331
            }
332
333
            if ($url == "") {
0 ignored issues
show
Unused Code introduced by
IfNode 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...
334
                throw new UnknownException(_("No ha sido posible obtener una respuesta de Pagantis"));
335
            } else { //if ($this->extraConfig['PAGANTIS_FORM_DISPLAY_TYPE'] == '0') {
336
                $output = "\n";
337
                $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

337
                $output.= /** @scrutinizer ignore-call */ tep_draw_hidden_field("formUrl", $url) . "\n";
Loading history...
338
                $output.= tep_draw_hidden_field("cancelUrl", $cancelUrl) . "\n";
339
                return $output;
340
            } /*else {
341
                $template_fields = array(
342
                    'url'         => $url,
343
                    'checkoutUrl' => $cancelUrl
344
                );
345
                wc_get_template('iframe.php', $template_fields, '', $this->template_path); //TODO
346
            }*/ //
347
        } catch (\Exception $exception) {
348
            var_dump($exception->getMessage());
0 ignored issues
show
Security Debugging Code introduced by
var_dump($exception->getMessage()) looks like debug code. Are you sure you do not want to remove it?
Loading history...
349
            exit;
0 ignored issues
show
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...
350
            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

350
            /** @scrutinizer ignore-call */ 
351
            tep_redirect($cancelUrl);
Loading history...
351
            return;
352
        }
353
    }
354
355
    /**
356
     *
357
     */
358
    public function before_process()
359
    {
360
        if (!$_POST) {
361
            die('aqui hemos llegado por order');
0 ignored issues
show
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...
362
        } else {
363
            echo "pasamos de largo pq es un POST y ya debe estar verificado";
364
        }
365
        exit;
0 ignored issues
show
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...
366
    }
367
368
    /**
369
    * Post-processing activities
370
    *
371
    * @return boolean
372
    */
373
    public function after_process()
374
    {
375
        global $insert_id, $order, $currencies;
376
        $this->order_id = $_SESSION['order_id'];
377
        $sql = sprintf("select json from %s where order_id='%s' order by id desc limit 1", TABLE_PAGANTIS, $this->order_id);
378
        $check_query = 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
        $check_query = /** @scrutinizer ignore-call */ tep_db_query($sql);
Loading history...
379
        while ($check = tep_db_fetch_array($check_query)) {
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

379
        while ($check = /** @scrutinizer ignore-call */ tep_db_fetch_array($check_query)) {
Loading history...
380
            $this->notification = json_decode(stripcslashes($check['json']), true);
0 ignored issues
show
Bug Best Practice introduced by
The property notification does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
381
        }
382
        if (MODULE_PAYMENT_PAGANTIS_TESTMODE == 'Test') {
0 ignored issues
show
Bug introduced by
The constant MODULE_PAYMENT_PAGANTIS_TESTMODE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
383
            $secret_key = MODULE_PAYMENT_PAGANTIS_TSK;
0 ignored issues
show
Bug introduced by
The constant MODULE_PAYMENT_PAGANTIS_TSK was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
384
            $public_key = MODULE_PAYMENT_PAGANTIS_TK;
0 ignored issues
show
Bug introduced by
The constant MODULE_PAYMENT_PAGANTIS_TK was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Unused Code introduced by
The assignment to $public_key is dead and can be removed.
Loading history...
385
        } else {
386
            $secret_key = MODULE_PAYMENT_PAGANTIS_PSK;
0 ignored issues
show
Bug introduced by
The constant MODULE_PAYMENT_PAGANTIS_PSK was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
387
            $public_key = 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...
388
        }
389
        $notififcation_check = true;
390
        $signature_check = sha1($secret_key.
391
        $this->notification['account_id'].
392
        $this->notification['api_version'].
393
        $this->notification['event'].
394
        $this->notification['data']['id']);
395
        $signature_check_sha512 = hash(
396
            'sha512',
397
            $secret_key.
398
            $this->notification['account_id'].
399
            $this->notification['api_version'].
400
            $this->notification['event'].
401
            $this->notification['data']['id']
402
        );
403
        if ($signature_check != $this->notification['signature'] && $signature_check_sha512 != $this->notification['signature']) {
404
            $notififcation_check = false;
405
        }
406
        //$this->notify('NOTIFY_PAYMENT_AUTHNETSIM_POSTPROCESS_HOOK');
407
        if ($notififcation_check && $this->notification['event'] == 'charge.created') {
408
            $sql = "insert into " . TABLE_ORDERS_STATUS_HISTORY . " (comments, orders_id, orders_status_id, customer_notified, date_added) values
0 ignored issues
show
Bug introduced by
The constant TABLE_ORDERS_STATUS_HISTORY was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
409
            ('".'Pagantis.  Transaction ID: ' .$this->notification['data']['id']."', ".$insert_id.", '".$this->order_status."', -1, now() )";
410
            tep_db_query($sql);
411
        }
412
        unset($_SESSION['order_id']);
413
        return false;
414
    }
415
416
    public function output_error()
417
    {
418
        return false;
419
    }
420
421
    public function check()
422
    {
423
        if (!isset($this->_check)) {
424
            $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

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

425
            $this->_check = /** @scrutinizer ignore-call */ tep_db_num_rows($check_query);
Loading history...
426
        }
427
        $this->install_pagantis_tables();
428
        return $this->_check;
429
    }
430
431
    /*
432
     * This is where you define module's configurations (displayed in admin).
433
     */
434
    public function install()
435
    {
436
        global $messageStack;
437
438
        if (defined('MODULE_PAYMENT_PAGANTIS_STATUS')) {
439
            $messageStack->add_session('Pagantis already installed.', 'error');
440
            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

440
            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

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

443
        /** @scrutinizer ignore-call */ 
444
        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...
444
        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())");
445
        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())");
446
        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 ('Include simulator', 'MODULE_PAYMENT_PAGANTIS_SIMULATOR', 'True', 'Do you want to include simulator in product page?', '6', '3', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");
447
448
        $this->install_pagantis_tables();
449
    }
450
451
    /**
452
     * Create the neccesary tables for the module
453
     */
454
    private function install_pagantis_tables()
455
    {
456
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS . " (
457
            `id` int(11) NOT NULL auto_increment,
458
            `insert_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
459
            `order_id` varchar(150) NOT NULL,
460
            `json` TEXT,
461
            PRIMARY KEY (id),
462
            KEY (order_id))";
463
        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

463
        /** @scrutinizer ignore-call */ 
464
        tep_db_query($sql);
Loading history...
464
465
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_LOG . " ( 
466
                          id int NOT NULL AUTO_INCREMENT, 
467
                          log text NOT NULL, 
468
                          createdAt timestamp DEFAULT CURRENT_TIMESTAMP, 
469
                          UNIQUE KEY id (id))";
470
        tep_db_query($sql);
471
472
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_CONFIG . " (
473
                            id int NOT NULL AUTO_INCREMENT, 
474
                            config varchar(60) NOT NULL, 
475
                            value varchar(100) NOT NULL, 
476
                            UNIQUE KEY id(id))";
477
        tep_db_query($sql);
478
        foreach ((array)$this->extraConfig as $configKey => $configValue) {
479
            $query = "INSERT INTO " . TABLE_PAGANTIS_CONFIG . " (config, value) values ($configKey, $configValue)";
480
            tep_db_query($query);
481
        }
482
483
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_ORDERS . " (
484
                            id int NOT NULL AUTO_INCREMENT, 
485
                            os_order_id varchar(50) NOT NULL, 
486
                            pmt_order_id varchar(50) NOT NULL, 
487
                            UNIQUE KEY id(id))";
488
        tep_db_query($sql);
489
490
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_CONCURRENCY . " (
491
                            id int NOT NULL,
492
                            `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
493
                            UNIQUE KEY id(id))";
494
        tep_db_query($sql);
495
    }
496
497
    /*
498
     * Standard functionality to uninstall the module.
499
     */
500
    public function remove()
501
    {
502
        $checkTable = tep_db_query("SHOW TABLES LIKE '".TABLE_PAGANTIS."'");
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

502
        $checkTable = /** @scrutinizer ignore-call */ tep_db_query("SHOW TABLES LIKE '".TABLE_PAGANTIS."'");
Loading history...
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
            tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");
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...
505
            tep_db_query("drop table " . TABLE_PAGANTIS);
506
        }
507
508
        $checkTable = tep_db_query("SHOW TABLES LIKE '".TABLE_PAGANTIS_LOG."'");
509
        if (tep_db_num_rows($checkTable) > 0) {
510
            tep_db_query("drop table " . TABLE_PAGANTIS_LOG);
511
        }
512
513
        $checkTable = tep_db_query("SHOW TABLES LIKE '".TABLE_PAGANTIS_CONFIG."'");
514
        if (tep_db_num_rows($checkTable) > 0) {
515
            tep_db_query("drop table " . TABLE_PAGANTIS_CONFIG);
516
        }
517
518
        $checkTable = tep_db_query("SHOW TABLES LIKE '".TABLE_PAGANTIS_ORDERS."'");
519
        if (tep_db_num_rows($checkTable) > 0) {
520
            tep_db_query("drop table " . TABLE_PAGANTIS_ORDERS);
521
        }
522
523
        $checkTable = tep_db_query("SHOW TABLES LIKE '".TABLE_PAGANTIS_CONCURRENCY."'");
524
        if (tep_db_num_rows($checkTable) > 0) {
525
            tep_db_query("drop table " . TABLE_PAGANTIS_CONCURRENCY);
526
        }
527
    }
528
529
    /**
530
    * Internal list of configuration keys used for configuration of the module
531
    *
532
    * @return array
533
    */
534
    public function keys()
535
    {
536
        return array('MODULE_PAYMENT_PAGANTIS_STATUS',
537
           'MODULE_PAYMENT_PAGANTIS_PK',
538
           'MODULE_PAYMENT_PAGANTIS_SK',
539
           'MODULE_PAYMENT_PAGANTIS_SIMULATOR');
540
    }
541
542
    /**
543
     * @return array
544
     */
545
    private function getOrders()
546
    {
547
        // extra parameters for logged users
548
        $sign_up = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $sign_up is dead and can be removed.
Loading history...
549
        $dob = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $dob is dead and can be removed.
Loading history...
550
        $order_total = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $order_total is dead and can be removed.
Loading history...
551
        $order_count = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $order_count is dead and can be removed.
Loading history...
552
        $this->is_guest = 'true';
553
        $result = array();
554
        if (trim($_SESSION['customer_id']) != '') {
555
            $this->is_guest = 'false';
556
            /*$sql = sprintf(
557
                "SELECT customers_info_date_account_created, customers_dob, customers_gender
558
                FROM %s
559
                JOIN %s ON customers_info.customers_info_id = customers.customers_id
560
                Where  customers.customers_id = %d",
561
                TABLE_CUSTOMERS,
562
                TABLE_CUSTOMERS_INFO,
563
                $_SESSION['customer_id']
564
            );
565
            $check_query = tep_db_query($sql);
566
            while ($check = tep_db_fetch_array($check_query)) {
567
                $sign_up = substr($check['customers_info_date_account_created'], 0, 10);
568
                $dob = substr($check['customers_dob'], 0, 10);
569
                $gender = $check['customers_gender'] == 'm' ? 'male' : 'female';
570
            }*/
571
            $sql = sprintf(
572
                "select orders_total.value from %s join %s on orders_status.orders_status_id = orders.orders_status
573
            join %s on orders.orders_id = orders_total.orders_id and orders_total.class = 'ot_total'
574
            where customers_id=%d and orders_status.orders_status_name in ('Processing','Delivered')
575
            order by orders.orders_id",
576
                TABLE_ORDERS_STATUS,
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...
577
                TABLE_ORDERS,
0 ignored issues
show
Bug introduced by
The constant TABLE_ORDERS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
578
                TABLE_ORDERS_TOTAL,
0 ignored issues
show
Bug introduced by
The constant TABLE_ORDERS_TOTAL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
579
                $_SESSION['customer_id']
580
            );
581
            $check_query = 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

581
            $check_query = /** @scrutinizer ignore-call */ tep_db_query($sql);
Loading history...
582
            $result = tep_db_fetch_array($check_query);
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

582
            $result = /** @scrutinizer ignore-call */ tep_db_fetch_array($check_query);
Loading history...
583
        }
584
        return $result;
585
    }
586
587
    /**
588
     * @param $orderId
589
     * @param $pmtOrderId
590
     *
591
     * @throws Exception
592
     */
593
    private function insertRow($orderId, $pmtOrderId)
594
    {
595
        $query = "select * from ". TABLE_PAGANTIS_ORDERS ." where os_order_id='$orderId'";
596
        $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

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

597
        $countResults = /** @scrutinizer ignore-call */ tep_db_num_rows($resultsSelect);
Loading history...
598
        if ($countResults == 0) {
599
            $query = "INSERT INTO " . TABLE_PAGANTIS_ORDERS ."(os_order_id, pmt_order_id) values ('$orderId', '$pmtOrderId')";
600
        } else {
601
            $query = "UPDATE " . TABLE_PAGANTIS_ORDERS . " set pmt_order_id='$pmtOrderId' where os_order_id='$orderId'";
602
        }
603
        tep_db_query($query);
604
    }
605
606
    private function getExtraConfig()
607
    {
608
        $checkTable = tep_db_query("SHOW TABLES LIKE '".TABLE_PAGANTIS."'");
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

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

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

613
            $resultArray = /** @scrutinizer ignore-call */ tep_db_fetch_array($result);
Loading history...
614
            $response    = array();
615
            foreach ((array)$resultArray as $key => $value) {
616
                $response[$key] = $value;
617
            }
618
        }
619
620
        return $response;
621
    }
622
623
    private function getPmtOrderId($osOrderId)
624
    {
625
        $result = '';
626
        $query = "select pmt_order_id from ". TABLE_PAGANTIS_ORDERS ." where os_order_id='$osOrderId'";
627
        $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

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

628
        while ($orderRow = /** @scrutinizer ignore-call */ tep_db_fetch_array($resultsSelect)) {
Loading history...
629
            $result = $orderRow['pmt_order_id'];
630
        }
631
        return $result;
632
    }
633
}
634