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

pagantis::output_error()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 2
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
use Pagantis\ModuleUtils\Exception\OrderNotFoundException;
4
use Pagantis\OrdersApiClient\Model\Order\User\Address;
5
use Pagantis\ModuleUtils\Exception\UnknownException;
6
7
define('TABLE_PAGANTIS_LOG', 'pagantis_log');
8
define('TABLE_PAGANTIS_CONFIG', 'pagantis_config');
9
define('TABLE_PAGANTIS_ORDERS', 'pagantis_order');
10
define('TABLE_PAGANTIS_CONCURRENCY', 'pagantis_concurrency');
11
define('__ROOT__', dirname(dirname(__FILE__)));
12
13
class pagantis
14
{
15
    /** @var  String $is_guest */
16
    public $is_guest;
17
18
    /** @var Array $extraConfig */
19
    public $extraConfig;
20
21
    /** @var String $form_action_url */
22
    public $form_action_url;
23
24
    /** @var String $base_url */
25
    public $base_url;
26
27
    /** @var String $os_order_reference */
28
    public $os_order_reference;
29
30
    /** @var notifyController $pgNotify */
31
    public $pgNotify;
32
33
    public $defaultConfigs = array('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_PROMOTION' => ''
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
        $this->description = $this->getDescription();
0 ignored issues
show
Bug Best Practice introduced by
The property description does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
60
61
        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...
62
            $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...
63
        } else {
64
            $this->title = $this->extraConfig['PAGANTIS_TITLE']; // Payment module title in Catalog
65
        }
66
67
        $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...
68
69
        $this->extraConfig = $this->getExtraConfig();
70
71
        $this->base_url = dirname(
72
            sprintf(
73
                "%s://%s%s%s",
74
                isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
75
                $_SERVER['SERVER_NAME'],
76
                isset($_SERVER['SERVER_PORT']) ? ":" . $_SERVER['SERVER_PORT'] : '',
77
                $_SERVER['REQUEST_URI']
78
            )
79
        );
80
81
        $this->form_action_url = $this->base_url . '/ext/modules/payment/pagantis/bypass.php';
82
    }
83
84
    /***************
85
     *
86
     * CLASS METHODS
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,
160
                   $payment, $comments, $customer_default_address_id, $cartID;
161
            $global_vars = array();
162
            $global_vars['customer_id'] = serialize($customer_id);
163
            $global_vars['sendTo'] = serialize($sendto);
164
            $global_vars['billTo'] = serialize($billto);
165
            $global_vars['cart'] = serialize($cart);
166
            $global_vars['languages_id'] = serialize($languages_id);
167
            $global_vars['currency'] = serialize($currency);
168
            $global_vars['currencies'] = serialize($currencies);
169
            $global_vars['shipping'] = serialize($shipping);
170
            $global_vars['payment'] = serialize($payment);
171
            $global_vars['comments'] = serialize($comments);
172
            $global_vars['$customer_default_address_id'] = serialize($customer_default_address_id);
173
            $global_vars['cartID'] = serialize($cartID);
174
            $global_vars['sessiontoken'] = serialize($_SESSION['sessiontoken']);
175
176
            if (!isset($order)) {
177
                throw new UnknownException("Order not found");
178
            }
179
180
            $id_hash = time() . serialize($order->products) . '' . serialize($order->customer) . '' . serialize($order->delivery);
181
            $this->os_order_reference = md5($id_hash);
182
            $_SESSION['order_id'] = $this->os_order_reference;
183
184
            $userAddress = new Address();
185
            $userAddress
186
                ->setZipCode($order->billing['postcode'])
187
                ->setFullName($order->billing['firstname'] . ' ' . $order->billing['lastname'])
188
                ->setCountryCode('ES')
189
                ->setCity($order->billing['city'])
190
                ->setAddress($order->billing['street_address'])
191
                ->setFixPhone($order->customer['telephone'])
192
                ->setMobilePhone($order->customer['telephone']);
193
194
            $orderBillingAddress = $userAddress;
195
196
            $orderShippingAddress = new Address();
197
            $orderShippingAddress
198
                ->setZipCode($order->delivery['postcode'])
199
                ->setFullName($order->billing['firstname'] . ' ' . $order->billing['lastname'])
200
                ->setCountryCode('ES')
201
                ->setCity($order->delivery['city'])
202
                ->setAddress($order->delivery['street_address'])
203
                ->setFixPhone($order->customer['telephone'])
204
                ->setMobilePhone($order->customer['telephone']);
205
206
            $orderUser = new \Pagantis\OrdersApiClient\Model\Order\User();
207
            $orderUser
208
                ->setAddress($userAddress)
209
                ->setFullName($order->billing['firstname'] . ' ' . $order->billing['lastname'])
210
                ->setBillingAddress($orderBillingAddress)
211
                ->setEmail($order->customer['email_address'])
212
                ->setFixPhone($order->customer['telephone'])
213
                ->setMobilePhone($order->customer['telephone'])
214
                ->setShippingAddress($orderShippingAddress);
215
216
            $previousOrders = $this->getOrders();
217
            foreach ((array)$previousOrders as $k => $previousOrder) {
218
                $orderHistory = new \Pagantis\OrdersApiClient\Model\Order\User\OrderHistory();
219
                $orderHistory
220
                    ->setAmount(intval(100 * $previousOrder['value']))
221
                    ->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

221
                    ->setDate(/** @scrutinizer ignore-type */ new \DateTime($previousOrder['date_purchased']));
Loading history...
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
229
            $promotedAmount = 0;
230
            foreach ($order->products as $item) {
231
                $promotedProduct = $this->isPromoted($item);
232
                $product = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product();
233
                $product
234
                    ->setAmount(intval(100 * number_format(($item['final_price'] * $item['qty']), 2)))
235
                    ->setQuantity(intval($item['qty']))
236
                    ->setDescription($item['name']);
237
                if ($promotedProduct) {
238
                    $promotedAmount+=$product->getAmount();
239
                }
240
                $details->addProduct($product);
241
            }
242
243
            $orderShoppingCart = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart();
244
            $orderShoppingCart
245
                ->setDetails($details)
246
                ->setOrderReference($this->os_order_reference)
247
                ->setPromotedAmount(0)
248
                ->setTotalAmount(intval($order->info['total'] * 100))
249
                ->setPromotedAmount($promotedAmount);
250
251
            $callback_url = $this->base_url.'/ext/modules/payment/pagantis/notify.php';
252
            $checkoutProcessUrl = htmlspecialchars_decode(
253
                tep_href_link(FILENAME_CHECKOUT_PROCESS, "order_id=$this->os_order_reference&from=order", 'SSL', true)
0 ignored issues
show
Bug introduced by
The function tep_href_link was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

318
            /** @scrutinizer ignore-call */ 
319
            tep_redirect($cancelUrl);
Loading history...
319
            return;
320
        }
321
    }
322
323
    /**
324
     * @throws Exception
325
     */
326
    public function before_process()
327
    {
328
        include_once('./ext/modules/payment/pagantis/notifyController.php');
329
        $this->pgNotify = new notifyController();
330
        $this->pgNotify->setOscommerceOrderId($_GET['order_id']);
331
        $this->pgNotify->setOrigin(isset($_GET['from']) ? ($_GET['from']) : 'order');
332
        $this->pgNotify->processInformation();
333
    }
334
335
    /**
336
     * Post-processing activities
337
     *
338
     * @return boolean
339
     */
340
    public function after_process()
341
    {
342
        $this->pgNotify->confirmInformation();
343
    }
344
345
    /**
346
     * @return bool
347
     */
348
    public function output_error()
349
    {
350
        return false;
351
    }
352
353
    /**
354
     * @return mixed
355
     */
356
    public function check()
357
    {
358
        if (!isset($this->_check)) {
359
            $query = "select * from ".TABLE_CONFIGURATION." where configuration_key = 'MODULE_PAYMENT_PAGANTIS_STATUS'";
0 ignored issues
show
Bug introduced by
The constant TABLE_CONFIGURATION was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
360
            $check_query = tep_db_query($query);
0 ignored issues
show
Bug introduced by
The function tep_db_query was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

360
            $check_query = /** @scrutinizer ignore-call */ tep_db_query($query);
Loading history...
361
            $this->_check = tep_db_num_rows($check_query);
0 ignored issues
show
Bug introduced by
The function tep_db_num_rows was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

361
            $this->_check = /** @scrutinizer ignore-call */ tep_db_num_rows($check_query);
Loading history...
Bug Best Practice introduced by
The property _check does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
362
        }
363
        $this->installPagantisTables();
364
        return $this->_check;
365
    }
366
367
    /**
368
     * This is where you define module's configurations (displayed in admin).
369
     */
370
    public function install()
371
    {
372
        global $messageStack;
373
374
        if (defined('MODULE_PAYMENT_PAGANTIS_STATUS')) {
375
            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

375
            tep_redirect(/** @scrutinizer ignore-call */ tep_href_link(FILENAME_MODULES, 'set=payment&module=pagantis', 'NONSSL'));
Loading history...
Bug introduced by
The function tep_redirect was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

375
            /** @scrutinizer ignore-call */ 
376
            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...
376
            return 'failed';
377
        }
378
379
        tep_db_query("insert into " . TABLE_CONFIGURATION . "
0 ignored issues
show
Bug introduced by
The function tep_db_query was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

379
        /** @scrutinizer ignore-call */ 
380
        tep_db_query("insert into " . TABLE_CONFIGURATION . "
Loading history...
Bug introduced by
The constant TABLE_CONFIGURATION was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
380
        (
381
            configuration_title,
382
            configuration_key,
383
            configuration_value,
384
            configuration_description,
385
            configuration_group_id,
386
            sort_order,
387
            set_function,
388
            date_added) 
389
        values 
390
        (
391
            'MODULE_PAYMENT_PAGANTIS_PANEL_TITLE',
392
            'MODULE_PAYMENT_PAGANTIS_STATUS',
393
            'True',
394
            '',
395
            '6',
396
            '0',
397
            'tep_cfg_select_option(array(\'True\',
398
            \'False\'),
399
            ',
400
            now()
401
        )");
402
        tep_db_query("insert into " . TABLE_CONFIGURATION . "
403
        (
404
            configuration_title,
405
            configuration_key,
406
            configuration_value,
407
            configuration_description,
408
            configuration_group_id,
409
            sort_order,
410
            date_added
411
        ) 
412
        values 
413
        (
414
            'Public Key',
415
            'MODULE_PAYMENT_PAGANTIS_PK',
416
            '',
417
            'MANDATORY. You can get in your pagantis profile',
418
            '6',
419
            '0',
420
            now()
421
        )");
422
        tep_db_query("insert into " . TABLE_CONFIGURATION . "
423
        (
424
            configuration_title,
425
            configuration_key,
426
            configuration_value,
427
            configuration_description,
428
            configuration_group_id,
429
            sort_order,
430
            date_added
431
        ) 
432
        values 
433
        (
434
            'Secret Key',
435
            'MODULE_PAYMENT_PAGANTIS_SK',
436
            '',
437
            'MANDATORY. You can get in your pagantis profile',
438
            '6',
439
            '0',
440
            now()
441
        )");
442
443
        $this->installPagantisTables();
444
445
        $this->installSimulator();
446
    }
447
448
    /**
449
     * Create the neccesary tables for the module
450
     */
451
    private function installPagantisTables()
452
    {
453
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_LOG . " ( 
454
                          id int NOT NULL AUTO_INCREMENT, 
455
                          log text NOT NULL, 
456
                          createdAt timestamp DEFAULT CURRENT_TIMESTAMP, 
457
                          UNIQUE KEY id (id))";
458
        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

458
        /** @scrutinizer ignore-call */ 
459
        tep_db_query($sql);
Loading history...
459
460
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_CONFIG . " (
461
                            id int NOT NULL AUTO_INCREMENT, 
462
                            config varchar(60) NOT NULL, 
463
                            value varchar(200) NOT NULL, 
464
                            UNIQUE KEY id(id))";
465
        tep_db_query($sql);
466
467
        // check if table has records
468
        $check_query = tep_db_query("select value from " . TABLE_PAGANTIS_CONFIG);
469
        if (tep_db_num_rows($check_query) === 0) {
0 ignored issues
show
Bug introduced by
The function tep_db_num_rows was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

469
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($check_query) === 0) {
Loading history...
470
            foreach ((array)$this->defaultConfigs as $configKey => $configValue) {
471
                $query = "INSERT INTO " . TABLE_PAGANTIS_CONFIG . "
472
                (
473
                    config,
474
                    value
475
                ) 
476
                values 
477
                (
478
                    '$configKey',
479
                    '$configValue'
480
                )";
481
                tep_db_query($query);
482
            }
483
        }
484
485
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_ORDERS . " (
486
                            id int NOT NULL AUTO_INCREMENT, 
487
                            os_order_id varchar(50), 
488
                            os_order_reference varchar(50) NOT NULL,
489
                            pagantis_order_id varchar(50) NOT NULL, 
490
                            globals text,
491
                            UNIQUE KEY id(id))";
492
        tep_db_query($sql);
493
494
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_CONCURRENCY . " (
495
                            id varchar(50) NOT NULL,
496
                            `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
497
                            UNIQUE KEY id(id))";
498
        tep_db_query($sql);
499
    }
500
501
    /**
502
     * Standard functionality to uninstall the module.
503
     */
504
    public function remove()
505
    {
506
        $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

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

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

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

566
            while ($orderRow = /** @scrutinizer ignore-call */ tep_db_fetch_array($resultsSelect)) {
Loading history...
567
                $response[] = $orderRow;
568
            }
569
        }
570
571
        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...
572
    }
573
574
    /**
575
     * @param $orderId
576
     * @param $pagantisOrderId
577
     * @param $globalVars
578
     */
579
    private function insertRow($orderId, $pagantisOrderId, $globalVars)
580
    {
581
        $query = "select * from " . TABLE_PAGANTIS_ORDERS . " where os_order_reference='$orderId'";
582
        $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

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

583
        $countResults = /** @scrutinizer ignore-call */ tep_db_num_rows($resultsSelect);
Loading history...
584
        if ($countResults == 0) {
585
            $query = "INSERT INTO " . TABLE_PAGANTIS_ORDERS . " 
586
                (os_order_reference, pagantis_order_id, globals) values ('$orderId', '$pagantisOrderId','$globalVars')";
587
        } else {
588
            $query = "UPDATE ".TABLE_PAGANTIS_ORDERS." set pagantis_order_id='$pagantisOrderId' 
589
                        where os_order_reference='$orderId'";
590
        }
591
        tep_db_query($query);
592
    }
593
594
    /**
595
     * @return array
596
     */
597
    private function getExtraConfig()
598
    {
599
        $checkTable = tep_db_query("SHOW TABLES LIKE '".TABLE_PAGANTIS_CONFIG."'");
0 ignored issues
show
Bug introduced by
The function tep_db_query was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

601
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkTable) > 0) {
Loading history...
602
            $query       = "select * from ".TABLE_PAGANTIS_CONFIG;
603
            $result      = tep_db_query($query);
604
            $response    = array();
605
            while ($resultArray = tep_db_fetch_array($result)) {
0 ignored issues
show
Bug introduced by
The function tep_db_fetch_array was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

605
            while ($resultArray = /** @scrutinizer ignore-call */ tep_db_fetch_array($result)) {
Loading history...
606
                $response[$resultArray['config']] = $resultArray['value'];
607
            }
608
        }
609
610
        return $response;
611
    }
612
613
    /**
614
     * @param $item
615
     *
616
     * @return bool
617
     */
618
    private function isPromoted($item)
619
    {
620
        $productId = explode('{', $item['id'], 1);
621
        $productId = $productId['0'];
622
623
        if ($this->extraConfig['PAGANTIS_PROMOTION'] == '') {
624
            $promotedProducts = array();
625
        } else {
626
            $promotedProducts = array_values((array)unserialize($this->extraConfig['PAGANTIS_PROMOTION']));
627
        }
628
629
        return (in_array($productId, $promotedProducts));
630
    }
631
632
    /**
633
     * @return string
634
     */
635
    private function getDescription()
636
    {
637
        $descriptionCode = "<img src=\"images/icon_info.gif\" border=\"0\" alt=\"Info\" title=\"Info\">&nbsp;<strong>Module version:</strong> $this->version<br/><br/>";
638
        $descriptionCode.= "<img src=\"images/icon_info.gif\" border=\"0\">&nbsp;<a href='https://developer.pagantis.com/' target=\"_blank\" style=\"text-decoration: underline; font-weight: bold;\">View Online Documentation</a><br/><br/>";
639
        $descriptionCode.= "<img src='images/icon_popup.gif'  border='0'>        <a href='http://pagantis.com' target='_blank' style='text-decoration: underline; font-weight: bold;'>Visit Pagantis Website</a><br/><br/><br/>";
640
        if (MODULE_PAYMENT_PAGANTIS_STATUS == 'True') {
0 ignored issues
show
Bug introduced by
The constant MODULE_PAYMENT_PAGANTIS_STATUS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
641
            $pagantisPromotionUrl = $this->base_url.'/ext/modules/payment/pagantis/promotion.php';
642
            $linkDescription = "Si desea gestionar los productos promocionados pulse aquí";
643
            $descriptionCode.= "<a href='$pagantisPromotionUrl'>$linkDescription</a>";
644
        }
645
646
        return $descriptionCode;
647
    }
648
649
650
    /**
651
     * @return bool
652
     */
653
    private function installSimulator()
654
    {
655
        $checkSimulator = tep_db_query("select configuration_key, configuration_value from " .TABLE_CONFIGURATION ." 
0 ignored issues
show
Bug introduced by
The constant TABLE_CONFIGURATION was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The function tep_db_query was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

655
        $checkSimulator = /** @scrutinizer ignore-call */ tep_db_query("select configuration_key, configuration_value from " .TABLE_CONFIGURATION ." 
Loading history...
656
                                    where configuration_key like 'MODULE_HEADER_TAGS_INSTALLED'
657
                                    and configuration_value like '%ht_pagantis.php%';");
658
        if (tep_db_num_rows($checkSimulator) > 0) {
0 ignored issues
show
Bug introduced by
The function tep_db_num_rows was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

658
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkSimulator) > 0) {
Loading history...
659
            return true;
660
        }
661
662
        $query = "UPDATE " . TABLE_CONFIGURATION . " set configuration_value = concat(configuration_value, ';ht_pagantis.php')
663
                        where configuration_key like 'MODULE_HEADER_TAGS_INSTALLED'";
664
        tep_db_query($query);
665
666
        tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable Pagantis Module', 'MODULE_HEADER_TAGS_PAGANTIS_STATUS', 'True', '', '6', '1', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");
667
    }
668
669
    private function uninstallSimulator()
670
    {
671
        $checkSimulator = tep_db_query("select configuration_key, configuration_value from " .TABLE_CONFIGURATION ." 
0 ignored issues
show
Bug introduced by
The function tep_db_query was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

671
        $checkSimulator = /** @scrutinizer ignore-call */ tep_db_query("select configuration_key, configuration_value from " .TABLE_CONFIGURATION ." 
Loading history...
Bug introduced by
The constant TABLE_CONFIGURATION was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
672
                                    where configuration_key like 'MODULE_HEADER_TAGS_INSTALLED'
673
                                    and configuration_value like '%ht_pagantis.php%';");
674
        if (tep_db_num_rows($checkSimulator) == 0) {
0 ignored issues
show
Bug introduced by
The function tep_db_num_rows was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

674
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkSimulator) == 0) {
Loading history...
675
            return true;
676
        }
677
678
        $query = "UPDATE " . TABLE_CONFIGURATION . " set configuration_value = REPLACE(configuration_value, ';ht_pagantis.php', '')
679
                        where configuration_key like 'MODULE_HEADER_TAGS_INSTALLED'";
680
        tep_db_query($query);
681
682
        $query = "delete from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_HEADER_TAGS_PAGANTIS_STATUS'";
683
        tep_db_query($query);
684
    }
685
}
686