Passed
Pull Request — master (#4)
by
unknown
08:12 queued 02:55
created

pagantis::remove()   A

Complexity

Conditions 5
Paths 16

Size

Total Lines 28
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
cc 5
eloc 16
c 5
b 0
f 0
nc 16
nop 0
dl 0
loc 28
rs 9.4222
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
        $this->extraConfig = $this->getExtraConfig();
61
62
        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...
63
            $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...
64
        } else {
65
            $this->title = $this->extraConfig['PAGANTIS_TITLE']; // Payment module title in Catalog
66
        }
67
68
        $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...
69
70
        $this->base_url = dirname(
71
            sprintf(
72
                "%s://%s%s%s",
73
                isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
74
                $_SERVER['SERVER_NAME'],
75
                isset($_SERVER['SERVER_PORT']) ? ":" . $_SERVER['SERVER_PORT'] : '',
76
                $_SERVER['REQUEST_URI']
77
            )
78
        );
79
80
        $this->form_action_url = $this->base_url . '/ext/modules/payment/pagantis/bypass.php';
81
    }
82
83
    /***************
84
     *
85
     * CLASS METHODS
86
     *
87
     **************/
88
    /**
89
     * Here you can implement using payment zones (refer to standard PayPal module as reference)
90
     */
91
    public function update_status()
92
    {
93
94
    }
95
96
    /*
97
    * Here you may define client side javascript that will verify any input fields you use in the payment method
98
    * selection page. Refer to standard cc module as reference (cc.php).
99
    */
100
    public function javascript_validation()
101
    {
102
        return false;
103
    }
104
105
    /*
106
    * Llamada cuando el usuario esta en la pantalla de eleccion de tipo de pago
107
     * This function outputs the payment method title/text and if required, the input fields.
108
    *
109
    * Si hay un pedido generado previamente y no confirmado, se borra
110
    * Caso de uso:
111
    * - el usuario llega a la pantalla de confirmacion
112
    * - se genera el pedido (pero no se genera entrada en orders_status_history)
113
    * - el usuario decide realizar algun cambio en su compra antes de pasar a pagantis
114
    * - entra de nuevo en la pantalla de seleccion de tipo de pago (puede elegir otra forma de pago)
115
    * - se comprueba que no exista el pedido generado anteriormente
116
    * - se borra el pedido que se habia generado inicialmente. Ya no es valido
117
    *
118
    */
119
    public function selection()
120
    {
121
        return array('id' => $this->code, 'module' => $this->title);
122
    }
123
124
    /*
125
    * Use this function implement any checks of any conditions after payment method has been selected. You most probably
126
    *  don't need to implement anything here.
127
    */
128
    public function pre_confirmation_check()
129
    {
130
        return false;
131
    }
132
133
    /*
134
     * Implement any checks or processing on the order information before proceeding to payment confirmation. You most
135
    probably don't need to implement anything here.
136
    * Llamada cuando el usuario entra en la pantalla de confirmacion
137
    *
138
    * Se genera el pedido:
139
    * - con el estado predefinido para el modulo pagantis
140
    * - sin notificacion a cliente ni administrador
141
    * - no se borra el carrito asociado al pedido
142
    *
143
    */
144
    public function confirmation()
145
    {
146
        return false;
147
    }
148
149
    /**
150
     * Build the data and actions to process when the "Submit" button is pressed on the order-confirmation screen.
151
     * This sends the data to the payment gateway for processing.
152
     * (These are hidden fields on the checkout confirmation page)
153
     */
154
    public function process_button()
155
    {
156
        try {
157
            include_once('./ext/modules/payment/pagantis/vendor/autoload.php');
158
            global $order, $customer_id, $sendto, $billto, $cart, $languages_id, $currency, $currencies, $shipping,
159
                   $payment, $comments, $customer_default_address_id, $cartID;
160
            $global_vars = array();
161
            $global_vars['customer_id'] = serialize($customer_id);
162
            $global_vars['sendTo'] = serialize($sendto);
163
            $global_vars['billTo'] = serialize($billto);
164
            $global_vars['cart'] = serialize($cart);
165
            $global_vars['languages_id'] = serialize($languages_id);
166
            $global_vars['currency'] = serialize($currency);
167
            $global_vars['currencies'] = serialize($currencies);
168
            $global_vars['shipping'] = serialize($shipping);
169
            $global_vars['payment'] = serialize($payment);
170
            $global_vars['comments'] = serialize($comments);
171
            $global_vars['$customer_default_address_id'] = serialize($customer_default_address_id);
172
            $global_vars['cartID'] = serialize($cartID);
173
            $global_vars['sessiontoken'] = serialize($_SESSION['sessiontoken']);
174
175
            if (!isset($order)) {
176
                throw new UnknownException("Order not found");
177
            }
178
179
            $id_hash = time() . serialize($order->products) . '' . serialize($order->customer) . '' . serialize($order->delivery);
180
            $this->os_order_reference = md5($id_hash);
181
            $_SESSION['order_id'] = $this->os_order_reference;
182
183
            $userAddress = new Address();
184
            $userAddress
185
                ->setZipCode($order->billing['postcode'])
186
                ->setFullName($order->billing['firstname'] . ' ' . $order->billing['lastname'])
187
                ->setCountryCode('ES')
188
                ->setCity($order->billing['city'])
189
                ->setAddress($order->billing['street_address'])
190
                ->setFixPhone($order->customer['telephone'])
191
                ->setMobilePhone($order->customer['telephone']);
192
193
            $orderBillingAddress = $userAddress;
194
195
            $orderShippingAddress = new Address();
196
            $orderShippingAddress
197
                ->setZipCode($order->delivery['postcode'])
198
                ->setFullName($order->billing['firstname'] . ' ' . $order->billing['lastname'])
199
                ->setCountryCode('ES')
200
                ->setCity($order->delivery['city'])
201
                ->setAddress($order->delivery['street_address'])
202
                ->setFixPhone($order->customer['telephone'])
203
                ->setMobilePhone($order->customer['telephone']);
204
205
            $orderUser = new \Pagantis\OrdersApiClient\Model\Order\User();
206
            $orderUser
207
                ->setAddress($userAddress)
208
                ->setFullName($order->billing['firstname'] . ' ' . $order->billing['lastname'])
209
                ->setBillingAddress($orderBillingAddress)
210
                ->setEmail($order->customer['email_address'])
211
                ->setFixPhone($order->customer['telephone'])
212
                ->setMobilePhone($order->customer['telephone'])
213
                ->setShippingAddress($orderShippingAddress);
214
215
            $previousOrders = $this->getOrders();
216
            foreach ((array)$previousOrders as $k => $previousOrder) {
217
                $orderHistory = new \Pagantis\OrdersApiClient\Model\Order\User\OrderHistory();
218
                $orderHistory
219
                    ->setAmount(intval(100 * $previousOrder['value']))
220
                    ->setDate(new \DateTime($previousOrder['date_purchased']));
0 ignored issues
show
Bug introduced by
new DateTime($previousOrder['date_purchased']) of type DateTime is incompatible with the type string expected by parameter $date of Pagantis\OrdersApiClient...OrderHistory::setDate(). ( Ignorable by Annotation )

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

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

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

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

317
            /** @scrutinizer ignore-call */ 
318
            tep_redirect($cancelUrl);
Loading history...
318
            return;
319
        }
320
    }
321
322
    /**
323
     * @throws Exception
324
     */
325
    public function before_process()
326
    {
327
        include_once('./ext/modules/payment/pagantis/notifyController.php');
328
        $this->pgNotify = new notifyController();
329
        $this->pgNotify->setOscommerceOrderId($_GET['order_id']);
330
        $this->pgNotify->setOrigin(isset($_GET['from']) ? ($_GET['from']) : 'order');
331
        $this->pgNotify->processInformation();
332
    }
333
334
    /**
335
     * Post-processing activities
336
     *
337
     * @return boolean
338
     */
339
    public function after_process()
340
    {
341
        $this->pgNotify->confirmInformation();
342
    }
343
344
    /**
345
     * @return bool
346
     */
347
    public function output_error()
348
    {
349
        return false;
350
    }
351
352
    /**
353
     * @return mixed
354
     */
355
    public function check()
356
    {
357
        if (!isset($this->_check)) {
358
            $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...
359
            $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

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

360
            $this->_check = /** @scrutinizer ignore-call */ tep_db_num_rows($check_query);
Loading history...
361
        }
362
        $this->installPagantisTables();
363
        return $this->_check;
364
    }
365
366
    /**
367
     * This is where you define module's configurations (displayed in admin).
368
     */
369
    public function install()
370
    {
371
        global $messageStack;
372
373
        if (defined('MODULE_PAYMENT_PAGANTIS_STATUS')) {
374
            tep_redirect(tep_href_link(FILENAME_MODULES, 'set=payment&module=pagantis', 'NONSSL'));
0 ignored issues
show
Bug introduced by
The function tep_redirect was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

374
            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...
375
            return 'failed';
376
        }
377
378
        tep_db_query("insert into " . 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

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

457
        /** @scrutinizer ignore-call */ 
458
        tep_db_query($sql);
Loading history...
458
459
        $sql = "CREATE TABLE IF NOT EXISTS " . TABLE_PAGANTIS_CONFIG . " (
460
                            id int NOT NULL AUTO_INCREMENT, 
461
                            config varchar(60) NOT NULL, 
462
                            value varchar(200) NOT NULL, 
463
                            UNIQUE KEY id(id))";
464
        tep_db_query($sql);
465
466
        // check if table has records
467
        $check_query = tep_db_query("select value from " . TABLE_PAGANTIS_CONFIG);
468
        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

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

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

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

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

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

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

582
        $countResults = /** @scrutinizer ignore-call */ tep_db_num_rows($resultsSelect);
Loading history...
583
        if ($countResults == 0) {
584
            $query = "INSERT INTO " . TABLE_PAGANTIS_ORDERS . " 
585
                (os_order_reference, pagantis_order_id, globals) values ('$orderId', '$pagantisOrderId','$globalVars')";
586
        } else {
587
            $query = "UPDATE ".TABLE_PAGANTIS_ORDERS." set pagantis_order_id='$pagantisOrderId' 
588
                        where os_order_reference='$orderId'";
589
        }
590
        tep_db_query($query);
591
    }
592
593
    /**
594
     * @return array
595
     */
596
    private function getExtraConfig()
597
    {
598
        $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

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

600
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkTable) > 0) {
Loading history...
601
            $query       = "select * from ".TABLE_PAGANTIS_CONFIG;
602
            $result      = tep_db_query($query);
603
            $response    = array();
604
            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

604
            while ($resultArray = /** @scrutinizer ignore-call */ tep_db_fetch_array($result)) {
Loading history...
605
                $response[$resultArray['config']] = $resultArray['value'];
606
            }
607
        }
608
609
        return $response;
610
    }
611
612
    /**
613
     * @param $item
614
     *
615
     * @return bool
616
     */
617
    private function isPromoted($item)
618
    {
619
        $productId = explode('{', $item['id'], 1);
620
        $productId = $productId['0'];
621
622
        if ($this->extraConfig['PAGANTIS_PROMOTION'] == '') {
623
            $promotedProducts = array();
624
        } else {
625
            $promotedProducts = array_values((array)unserialize($this->extraConfig['PAGANTIS_PROMOTION']));
626
        }
627
628
        return (in_array($productId, $promotedProducts));
629
    }
630
631
    /**
632
     * @return string
633
     */
634
    private function getDescription()
635
    {
636
        $descriptionCode = "<img src=\"images/icon_info.gif\" border=\"0\" alt=\"Info\" title=\"Info\">&nbsp;<strong>Module version:</strong> $this->version<br/><br/>";
637
        $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/>";
638
        $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/>";
639
        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...
640
            $pagantisPromotionUrl = $this->base_url.'/ext/modules/payment/pagantis/promotion.php';
641
            $linkDescription = "Si desea gestionar los productos promocionados pulse aquí";
642
            $descriptionCode.= "<a href='$pagantisPromotionUrl'>$linkDescription</a>";
643
        }
644
645
        return $descriptionCode;
646
    }
647
648
649
    /**
650
     * @return bool
651
     */
652
    private function installSimulator()
653
    {
654
        $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

654
        $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...
655
                                    where configuration_key like 'MODULE_HEADER_TAGS_INSTALLED'
656
                                    and configuration_value like '%ht_pagantis.php%';");
657
        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

657
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkSimulator) > 0) {
Loading history...
658
            return true;
659
        }
660
661
        $query = "UPDATE " . TABLE_CONFIGURATION . " set configuration_value = concat(configuration_value, ';ht_pagantis.php')
662
                        where configuration_key like 'MODULE_HEADER_TAGS_INSTALLED'";
663
        tep_db_query($query);
664
665
        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())");
666
    }
667
668
    private function uninstallSimulator()
669
    {
670
        $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

670
        $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...
671
                                    where configuration_key like 'MODULE_HEADER_TAGS_INSTALLED'
672
                                    and configuration_value like '%ht_pagantis.php%';");
673
        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

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