Passed
Pull Request — master (#102)
by Raúl
04:58
created

Pagantis::checkDatabaseTables()   B

Complexity

Conditions 8
Paths 51

Size

Total Lines 33
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 25
c 1
b 0
f 0
nc 51
nop 0
dl 0
loc 33
rs 8.4444
1
<?php
2
/**
3
 * This file is part of the official Pagantis module for PrestaShop.
4
 *
5
 * @author    Pagantis <[email protected]>
6
 * @copyright 2019 Pagantis
7
 * @license   proprietary
8
 */
9
10
if (!defined('_PS_VERSION_')) {
11
    exit;
12
}
13
14
define('_PS_PAGANTIS_DIR', _PS_MODULE_DIR_. '/pagantis');
0 ignored issues
show
Bug introduced by
The constant _PS_MODULE_DIR_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
15
define('PROMOTIONS_CATEGORY', 'pagantis-promotion-product');
16
define('PROMOTIONS_CATEGORY_NAME', 'Pagantis Promoted Product');
17
18
require _PS_PAGANTIS_DIR.'/vendor/autoload.php';
19
20
/**
21
 * Class Pagantis
22
 */
23
class Pagantis extends PaymentModule
0 ignored issues
show
Bug introduced by
The type PaymentModule was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
24
{
25
    /**
26
     * @var string
27
     */
28
    public $url = 'https://pagantis.com';
29
30
    /**
31
     * @var bool
32
     */
33
    public $bootstrap = true;
34
35
    /** @var string $language */
36
    public $language;
37
38
    /**
39
     * Default module advanced configuration values
40
     *
41
     * @var array
42
     */
43
    public $defaultConfigs = array(
44
        'URL_OK' => '',
45
        'URL_KO' => '',
46
        'ALLOWED_COUNTRIES' => 'a:3:{i:0;s:2:"es";i:1;s:2:"it";i:2;s:2:"fr";}',
47
        'PRODUCTS' => 'P4X,PAGANTIS',
48
        'P4X' => '{
49
            "CODE": "P4X",
50
            "TITLE": "Pay in 4 installments, without cost",
51
            "SIMULATOR_TITLE": "up to 4 payments of",
52
            "SIMULATOR_SUBTITLE": "without cost with",
53
            "SIMULATOR_DISPLAY_TYPE": "p4x",
54
            "SIMULATOR_DISPLAY_IMAGE": "https://cdn.digitalorigin.com/assets/master/logos/pg-favicon.png",
55
            "SIMULATOR_DISPLAY_TYPE_CHECKOUT": "sdk.simulator.types.CHECKOUT_PAGE",
56
            "SIMULATOR_START_INSTALLMENTS": "4",
57
            "SIMULATOR_CSS_PRICE_SELECTOR": "default",
58
            "SIMULATOR_CSS_QUANTITY_SELECTOR": "default",
59
            "SIMULATOR_CSS_PRODUCT_PAGE_STYLES": "",
60
            "SIMULATOR_CSS_CHECKOUT_PAGE_STYLES": "",
61
            "SIMULATOR_DISPLAY_MAX_AMOUNT": "800",
62
            "FORM_DISPLAY_TYPE" : "0",
63
            "DISPLAY_MIN_AMOUNT": "0",
64
            "DISPLAY_MAX_AMOUNT": "800",
65
            "SIMULATOR_THOUSAND_SEPARATOR": ".",
66
            "SIMULATOR_DECIMAL_SEPARATOR": ","
67
            }',
68
        'PAGANTIS' => '{
69
            "CODE": "PAGANTIS",
70
            "TITLE": "Instant Financing",
71
            "SIMULATOR_TITLE": "Instant Financing",
72
            "SIMULATOR_SUBTITLE": "",
73
            "SIMULATOR_DISPLAY_TYPE": "sdk.simulator.types.PRODUCT_PAGE",
74
            "SIMULATOR_DISPLAY_TYPE_CHECKOUT": "sdk.simulator.types.CHECKOUT_PAGE",
75
            "SIMULATOR_DISPLAY_SKIN": "sdk.simulator.skins.BLUE",
76
            "SIMULATOR_START_INSTALLMENTS": "3",
77
            "SIMULATOR_CSS_POSITION_SELECTOR": "default",
78
            "SIMULATOR_DISPLAY_CSS_POSITION": "sdk.simulator.positions.INNER",
79
            "SIMULATOR_CSS_PRICE_SELECTOR": "default",
80
            "SIMULATOR_CSS_QUANTITY_SELECTOR": "default",
81
            "SIMULATOR_CSS_PRODUCT_PAGE_STYLES": "",
82
            "SIMULATOR_CSS_CHECKOUT_PAGE_STYLES": "",   
83
            "SIMULATOR_DISPLAY_MAX_AMOUNT": "1500",
84
            "FORM_DISPLAY_TYPE" : "0",
85
            "DISPLAY_MIN_AMOUNT": "0",
86
            "DISPLAY_MAX_AMOUNT": "1500",
87
            "PROMOTION_EXTRA": "Finance this product <span class=pg-no-interest>without interest!</span>",
88
            "SIMULATOR_THOUSAND_SEPARATOR": ".",
89
            "SIMULATOR_DECIMAL_SEPARATOR": ","
90
            }',
91
    );
92
    /**
93
     * @var null $shippingAddress
94
     */
95
    protected $shippingAddress = null;
96
    /**
97
     * @var null $billingAddress
98
     */
99
    protected $billingAddress = null;
100
101
    /**
102
     * @var array $allowedCountries
103
     */
104
    protected $allowedCountries = array();
105
106
    /**
107
     * Pagantis constructor.
108
     *
109
     * Define the module main properties so that prestashop understands what are the module requirements
110
     * and how to manage the module.
111
     *
112
     */
113
    public function __construct()
114
    {
115
        $this->name = 'pagantis';
0 ignored issues
show
Bug Best Practice introduced by
The property name does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
116
        $this->tab = 'payments_gateways';
0 ignored issues
show
Bug Best Practice introduced by
The property tab does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
117
        $this->version = '8.6.11';
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...
118
        $this->author = 'Pagantis';
0 ignored issues
show
Bug Best Practice introduced by
The property author does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
119
        $this->currencies = true;
0 ignored issues
show
Bug Best Practice introduced by
The property currencies does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
120
        $this->currencies_mode = 'checkbox';
0 ignored issues
show
Bug Best Practice introduced by
The property currencies_mode does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
121
        $this->module_key = '2b9bc901b4d834bb7069e7ea6510438f';
0 ignored issues
show
Bug Best Practice introduced by
The property module_key does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
122
        $this->ps_versions_compliancy = array('min' => '1.5', 'max' => _PS_VERSION_);
0 ignored issues
show
Bug introduced by
The constant _PS_VERSION_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug Best Practice introduced by
The property ps_versions_compliancy does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
123
        $this->displayName = $this->l('Pagantis');
0 ignored issues
show
Bug Best Practice introduced by
The property displayName does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
124
        $this->description = $this->l(
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...
125
            'Instant, easy and effective financial tool for your customers'
126
        );
127
128
        $current_context = Context::getContext();
0 ignored issues
show
Bug introduced by
The type Context was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
129
        if (!is_null($current_context->controller) && $current_context->controller->controller_type != 'front') {
130
            $sql_file = dirname(__FILE__).'/sql/install.sql';
131
            $this->loadSQLFile($sql_file);
132
            $this->checkDatabaseTables();
133
            $this->checkEnvVariables();
134
            $this->migrate();
135
            $this->checkHooks();
136
            $this->checkPromotionCategory();
137
        }
138
139
        parent::__construct();
140
141
        $this->getUserLanguage();
142
    }
143
144
    /**
145
     * Configure the variables for Pagantis payment method.
146
     *
147
     * @return bool
148
     */
149
    public function install()
150
    {
151
        if (!extension_loaded('curl')) {
152
            $this->_errors[] =
0 ignored issues
show
Bug Best Practice introduced by
The property _errors does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
153
                $this->l('You have to enable the cURL extension on your server to install this module');
154
            return false;
155
        }
156
        if (!version_compare(phpversion(), '5.3.0', '>=')) {
157
            $this->_errors[] = $this->l('The PHP version bellow 5.3.0 is not supported');
158
            return false;
159
        }
160
161
        $products = explode(',', Pagantis::getExtraConfig('PRODUCTS', null));
162
        foreach ($products as $product) {
163
            $code = Tools::strtolower(Pagantis::getExtraConfig('CODE', $product));
0 ignored issues
show
Bug introduced by
The type Tools was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
164
            if ($code === 'p4x') {
165
                Configuration::updateValue($code . '_simulator_is_enabled', 1);
0 ignored issues
show
Bug introduced by
The type Configuration was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
166
            }
167
            Configuration::updateValue($code . '_is_enabled', 0);
168
            Configuration::updateValue($code . '_public_key', '');
169
            Configuration::updateValue($code . '_private_key', '');
170
        }
171
172
        $return =  (parent::install()
173
            && $this->registerHook('displayShoppingCart')
174
            && $this->registerHook('paymentOptions')
175
            && $this->registerHook('displayProductButtons')
176
            && $this->registerHook('displayProductPriceBlock')
177
            && $this->registerHook('displayOrderConfirmation')
178
            && $this->registerHook('header')
179
        );
180
181
        if ($return && _PS_VERSION_ < "1.7") {
0 ignored issues
show
Bug introduced by
The constant _PS_VERSION_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
182
            $this->registerHook('payment');
183
        }
184
185
        return $return;
186
    }
187
188
    /**
189
     * Remove the production private api key and remove the files
190
     *
191
     * @return bool
192
     */
193
    public function uninstall()
194
    {
195
        Configuration::deleteByName('4x_public_key');
196
        Configuration::deleteByName('12x_public_key');
197
        Configuration::deleteByName('4x_public_key');
198
        Configuration::deleteByName('12x_public_key');
199
        Configuration::deleteByName('12x_simulator_is_enabled');
200
        $sql_file = dirname(__FILE__).'/sql/uninstall.sql';
201
        $this->loadSQLFile($sql_file);
202
203
204
        return parent::uninstall();
205
    }
206
207
    /**
208
     * Migrate the configs of simple 8x module to multiproduct
209
     */
210
    public function migrate()
211
    {
212
    }
213
214
    /**
215
     * Check if new hooks used in new 7x versions are enabled and activate them if needed
216
     *
217
     * @throws PrestaShopDatabaseException
218
     */
219
    public function checkHooks()
220
    {
221
        try {
222
            $sql_content = 'select * from ' . _DB_PREFIX_. 'hook_module where 
0 ignored issues
show
Bug introduced by
The constant _DB_PREFIX_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
223
            id_module = \'' . Module::getModuleIdByName($this->name) . '\' and 
0 ignored issues
show
Bug introduced by
The type Module was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
224
            id_shop = \'' . Shop::getContextShopID() . '\' and 
0 ignored issues
show
Bug introduced by
The type Shop was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
225
            id_hook = \'' . Hook::getIdByName('header') . '\'';
0 ignored issues
show
Bug introduced by
The type Hook was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
226
            $hook_exists = Db::getInstance()->ExecuteS($sql_content);
0 ignored issues
show
Bug introduced by
The type Db was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
227
            if (empty($hook_exists)) {
228
                $sql_insert = 'insert into ' . _DB_PREFIX_.  'hook_module 
229
            (id_module, id_shop, id_hook, position)
230
            values
231
            (\''. Module::getModuleIdByName($this->name) . '\',
232
            \''. Shop::getContextShopID() . '\',
233
            \''. Hook::getIdByName('header') . '\',
234
            150)';
235
                Db::getInstance()->execute($sql_insert);
236
            }
237
238
            $sql_content = 'select * from ' . _DB_PREFIX_. 'hook_module where 
239
            id_module = \'' . Module::getModuleIdByName($this->name) . '\' and 
240
            id_shop = \'' . Shop::getContextShopID() . '\' and 
241
            id_hook = \'' . Hook::getIdByName('displayProductPriceBlock') . '\'';
242
            $hook_exists = Db::getInstance()->ExecuteS($sql_content);
243
            if (empty($hook_exists)) {
244
                $sql_insert = 'insert into ' . _DB_PREFIX_.  'hook_module 
245
            (id_module, id_shop, id_hook, position)
246
            values
247
            (\''. Module::getModuleIdByName($this->name) . '\',
248
            \''. Shop::getContextShopID() . '\',
249
            \''. Hook::getIdByName('displayProductPriceBlock') . '\',
250
            160)';
251
                Db::getInstance()->execute($sql_insert);
252
            }
253
        } catch (\Exception $exception) {
254
            // continue without errors
255
        }
256
    }
257
258
    /**
259
     * @throws PrestaShopDatabaseException
260
     */
261
    public function checkEnvVariables()
262
    {
263
        $sql_content = 'select * from ' . _DB_PREFIX_. 'pagantis_config';
0 ignored issues
show
Bug introduced by
The constant _DB_PREFIX_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
264
        $dbConfigs = Db::getInstance()->executeS($sql_content);
265
266
        // Convert a multimple dimension array for SQL insert statements into a simple key/value
267
        $simpleDbConfigs = array();
268
        foreach ($dbConfigs as $config) {
269
            $simpleDbConfigs[$config['config']] = $config['value'];
270
        }
271
        $newConfigs = array_diff_key($this->defaultConfigs, $simpleDbConfigs);
272
        if (!empty($newConfigs)) {
273
            $data = array();
274
            foreach ($newConfigs as $key => $value) {
275
                $data[] = array(
276
                    'config' => $key,
277
                    'value' => $value,
278
                );
279
            }
280
            Db::getInstance()->insert('pagantis_config', $data);
281
        }
282
    }
283
284
    /**
285
     * @param $sql_file
286
     * @return bool
287
     */
288
    public function loadSQLFile($sql_file)
289
    {
290
        $sql_content = Tools::file_get_contents($sql_file);
291
        $sql_content = str_replace('PREFIX_', _DB_PREFIX_, $sql_content);
0 ignored issues
show
Bug introduced by
The constant _DB_PREFIX_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
292
        $sql_requests = preg_split("/;\s*[\r\n]+/", $sql_content);
293
294
        $result = true;
295
        foreach ($sql_requests as $request) {
296
            if (!empty($request)) {
297
                $result &= Db::getInstance()->execute(trim($request));
298
            }
299
        }
300
301
        return $result;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $result also could return the type integer which is incompatible with the documented return type boolean.
Loading history...
302
    }
303
304
    /**
305
     * checkDatabaseTables INTEGRITY
306
     */
307
    public function checkDatabaseTables()
308
    {
309
        try {
310
            $tableName = _DB_PREFIX_.'pagantis_order';
0 ignored issues
show
Bug introduced by
The constant _DB_PREFIX_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
311
            $sql = "show tables like '"   . $tableName . "'";
312
            $data = Db::getInstance()->ExecuteS($sql);
313
            if (count($data) > 0) {
314
                $sql = "desc " . $tableName;
315
                $data = Db::getInstance()->ExecuteS($sql);
316
                if (count($data) == 2) {
317
                    $sql = "ALTER TABLE $tableName ADD COLUMN ps_order_id VARCHAR(60) AFTER order_id";
318
                    Db::getInstance()->Execute($sql);
319
                }
320
                if (count($data) == 3) {
321
                    $sql = "ALTER TABLE " . $tableName . " ADD COLUMN  token VARCHAR(32) NOT NULL AFTER order_id";
322
                    Db::getInstance()->Execute($sql);
323
                    $sql = "ALTER TABLE ps_pagantis_order DROP PRIMARY KEY, ADD PRIMARY KEY(id, order_id);";
324
                    Db::getInstance()->Execute($sql);
325
                }
326
            }
327
            $tableName = _DB_PREFIX_.'pagantis_config';
328
            $sql = "show tables like '"   . $tableName . "'";
329
            $data = Db::getInstance()->ExecuteS($sql);
330
            if (count($data) > 0) {
331
                $sql = "desc "   . $tableName;
332
                $data = Db::getInstance()->ExecuteS($sql);
333
                if (count($data) === 3 && $data[2]['Type'] !== 'varchar(5000)') {
334
                    $sql = "ALTER TABLE $tableName MODIFY `value` VARCHAR(5000)";
335
                    Db::getInstance()->Execute($sql);
336
                }
337
                // return because pagantis tables exisit so load the sqlfile is not needed
338
            }
339
        } catch (\Exception $exception) {
340
            // do nothing
341
        }
342
    }
343
344
    /**
345
     * Check amount of order > minAmount
346
     * Check valid currency
347
     * Check API variables are set
348
     *
349
     * @param string $product
350
     * @return bool
351
     */
352
    public function isPaymentMethodAvailable($product = 'p4x')
353
    {
354
        $configs = json_decode(Pagantis::getExtraConfig($product, null), true);
355
        $cart                      = $this->context->cart;
356
        $currency                  = new Currency($cart->id_currency);
0 ignored issues
show
Bug introduced by
The type Currency was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
357
        $availableCurrencies       = array('EUR');
358
        $pagantisDisplayMinAmount  = $configs['DISPLAY_MIN_AMOUNT'];
359
        $pagantisDisplayMaxAmount  = $configs['DISPLAY_MAX_AMOUNT'];
360
        $pagantisPublicKey         = Configuration::get(Tools::strtolower($configs['CODE']) . '_public_key');
361
        $pagantisPrivateKey        = Configuration::get(Tools::strtolower($configs['CODE']) . '_private_key');
362
        $this->allowedCountries    = unserialize(Pagantis::getExtraConfig('ALLOWED_COUNTRIES', null));
363
        $this->getUserLanguage();
364
        return (
365
            $cart->getOrderTotal() >= $pagantisDisplayMinAmount &&
366
            ($cart->getOrderTotal() <= $pagantisDisplayMaxAmount || $pagantisDisplayMaxAmount == '0') &&
367
            in_array($currency->iso_code, $availableCurrencies) &&
368
            in_array(Tools::strtolower($this->language), $this->allowedCountries) &&
369
            $pagantisPublicKey &&
370
            $pagantisPrivateKey
371
        );
372
    }
373
374
    /**
375
     * @param Cart $cart
376
     *
377
     * @return array
378
     * @throws Exception
379
     */
380
    private function getButtonTemplateVars(Cart $cart)
0 ignored issues
show
Bug introduced by
The type Cart was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
381
    {
382
        $currency = new Currency(($cart->id_currency));
383
384
        return array(
385
            'button' => '#payment_button',
386
            'currency_iso' => $currency->iso_code,
387
            'cart_total' => $cart->getOrderTotal(),
388
        );
389
    }
390
391
    /**
392
     * Header hook
393
     */
394
    public function hookHeader()
395
    {
396
397
        $url = 'https://cdn.pagantis.com/js/pg-v2/sdk.js';
398
        if (_PS_VERSION_ >= "1.7") {
0 ignored issues
show
Bug introduced by
The constant _PS_VERSION_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
399
            $this->context->controller->registerJavascript(
400
                sha1(mt_rand(1, 90000)),
401
                $url,
402
                array('server' => 'remote')
403
            );
404
        } else {
405
            $this->context->controller->addJS($url);
406
        }
407
    }
408
409
    /**
410
     * @return array
411
     * @throws Exception
412
     */
413
    public function hookPaymentOptions()
414
    {
415
        /** @var Cart $cart */
416
        $cart = $this->context->cart;
417
        $this->shippingAddress = new Address($cart->id_address_delivery);
0 ignored issues
show
Bug introduced by
The type Address was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
Documentation Bug introduced by
It seems like new Address($cart->id_address_delivery) of type Address is incompatible with the declared type null of property $shippingAddress.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
418
        $this->billingAddress = new Address($cart->id_address_invoice);
0 ignored issues
show
Documentation Bug introduced by
It seems like new Address($cart->id_address_invoice) of type Address is incompatible with the declared type null of property $billingAddress.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
419
420
        $orderTotal = $cart->getOrderTotal();
421
        $promotedAmount = 0;
422
        $link = $this->context->link;
423
        $items = $cart->getProducts(true);
424
        foreach ($items as $item) {
425
            $itemCategories = ProductCore::getProductCategoriesFull($item['id_product']);
0 ignored issues
show
Bug introduced by
The type ProductCore was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
426
            if (in_array(PROMOTIONS_CATEGORY_NAME, $this->arrayColumn($itemCategories, 'name')) !== false) {
427
                $productId = $item['id_product'];
428
                $promotedAmount += Product::getPriceStatic($productId);
0 ignored issues
show
Bug introduced by
The type Product was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
429
            }
430
        }
431
432
        $return = array();
433
        $this->context->smarty->assign($this->getButtonTemplateVars($cart));
434
        $products = explode(',', Pagantis::getExtraConfig('PRODUCTS', null));
435
        $templateConfigs = array();
436
        foreach ($products as $product) {
437
            if ($this->isPaymentMethodAvailable($product)) {
438
                $productConfigs = Pagantis::getExtraConfig($product, null);
439
                $productConfigs = json_decode($productConfigs, true);
440
                $publicKey = Configuration::get(Tools::strtolower($productConfigs['CODE']) . '_public_key');
441
                $simulatorIsEnabled = Configuration::get(Tools::strtolower($productConfigs['CODE']) . '_simulator_is_enabled');
442
                $isEnabled = Configuration::get(Tools::strtolower($productConfigs['CODE']) . '_is_enabled');
443
444
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_TITLE'] = $this->l($productConfigs['TITLE']);
445
                unset($productConfigs['TITLE']);
446
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_AMOUNT'] = $orderTotal;
447
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_PROMOTED_AMOUNT'] = $promotedAmount;
448
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_LOCALE'] = $this->language;
449
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_COUNTRY'] = $this->language;
450
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_PUBLIC_KEY'] = $publicKey;
451
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_SIMULATOR_IS_ENABLED'] = $simulatorIsEnabled;
452
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_IS_ENABLED'] = $isEnabled;
453
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_LOGO'] = 'https://cdn.digitalorigin.com/assets/master/logos/pg-favicon.png';
454
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_PAYMENT_URL'] = $link->getModuleLink('pagantis', 'payment') . '&product=' . $productConfigs['CODE'];
455
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_PS_VERSION'] = str_replace('.', '-', Tools::substr(_PS_VERSION_, 0, 3));
0 ignored issues
show
Bug introduced by
The constant _PS_VERSION_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
456
457
                foreach ($productConfigs as $productConfigKey => $productConfigValue) {
458
                    $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . "_" . $productConfigKey] = $productConfigValue;
459
                }
460
                $this->context->smarty->assign($templateConfigs);
461
462
                $paymentOption = new PrestaShop\PrestaShop\Core\Payment\PaymentOption();
0 ignored issues
show
Bug introduced by
The type PrestaShop\PrestaShop\Core\Payment\PaymentOption was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
463
                $uri = $link->getModuleLink('pagantis', 'payment');
464
                if (strpos($uri, '?') !== false) {
465
                    $uri .= '&product=' . $productConfigs['CODE'];
466
                } else {
467
                    $uri .= '?product=' . $productConfigs['CODE'];
468
                }
469
                $paymentOption
470
                    ->setCallToActionText($templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_TITLE'])
471
                    ->setAction($uri)
472
                    ->setLogo($templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_LOGO'])
473
                    ->setModuleName(__CLASS__)
474
                    ->setAdditionalInformation(
475
                        $this->fetch('module:pagantis/views/templates/hook/checkout-' . Tools::strtolower($productConfigs['CODE']) . '.tpl')
476
                    )
477
                ;
478
                $return[] = $paymentOption;
479
            }
480
        }
481
        if (count($return) === 0) {
482
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type array.
Loading history...
483
        }
484
        return $return;
485
    }
486
487
    /**
488
     * Get the form for editing the BackOffice options of the module
489
     *
490
     * @return array
491
            */
492
    private function getConfigForm()
493
    {
494
        $products = explode(',', Pagantis::getExtraConfig('PRODUCTS', null));
495
        $inputs = array();
496
        foreach ($products as $product) {
497
            $code = Tools::strtolower(Pagantis::getExtraConfig('CODE', $product));
498
            $inputs[] = array(
499
                'name' => $code .'_is_enabled',
500
                'type' =>  (version_compare(_PS_VERSION_, '1.6')<0) ?'radio' :'switch',
0 ignored issues
show
Bug introduced by
The constant _PS_VERSION_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
501
                'label' => $this->l('Module is enabled ' . $code),
502
                'prefix' => '<i class="icon icon-key"></i>',
503
                'class' => 't',
504
                'required' => true,
505
                'values'=> array(
506
                    array(
507
                        'id' => $code .'_is_enabled_true',
508
                        'value' => 1,
509
                        'label' => $this->l('Yes', get_class($this), null, false),
510
                    ),
511
                    array(
512
                        'id' => $code . '_is_enabled_false',
513
                        'value' => 0,
514
                        'label' => $this->l('No', get_class($this), null, false),
515
                    ),
516
                )
517
            );
518
            $inputs[] = array(
519
                'name' => $code . '_public_key',
520
                'suffix' => $this->l('ex: pk_fd53cd467ba49022e4gf215e'),
521
                'type' => 'text',
522
                'size' => 60,
523
                'label' => $this->l('Public Key ' . $code),
524
                'prefix' => '<i class="icon icon-key"></i>',
525
                'col' => 6,
526
                'required' => true,
527
            );
528
            $inputs[] = array(
529
                'name' => $code . '_private_key',
530
                'suffix' => $this->l('ex: 21e5723a97459f6a'),
531
                'type' => 'text',
532
                'size' => 60,
533
                'label' => $this->l('Private Key ' . $code),
534
                'prefix' => '<i class="icon icon-key"></i>',
535
                'col' => 6,
536
                'required' => true,
537
            );
538
            if ($code !== "p4x") {
539
                $inputs[] = array(
540
                    'name' => $code . '_simulator_is_enabled',
541
                    'type' => (version_compare(_PS_VERSION_, '1.6')<0) ?'radio' :'switch',
542
                    'label' => $this->l('Simulator is enabled ' . $code),
543
                    'prefix' => '<i class="icon icon-key"></i>',
544
                    'class' => 't',
545
                    'required' => true,
546
                    'values'=> array(
547
                        array(
548
                            'id' => $code . '_simulator_is_enabled_on',
549
                            'value' => 1,
550
                            'label' => $this->l('Yes'),
551
                        ),
552
                        array(
553
                            'id' => $code . '_simulator_is_enabled_off',
554
                            'value' => 0,
555
                            'label' => $this->l('No'),
556
                        ),
557
                    )
558
                );
559
            }
560
        }
561
        $return = array(
562
            'form' => array(
563
                'legend' => array(
564
                    'title' => $this->l('Basic Settings'),
565
                    'icon' => 'icon-cogs',
566
                ),
567
                'input' => $inputs,
568
                'submit' => array(
569
                    'title' => $this->l('Save'),
570
                )
571
            )
572
        );
573
        return $return;
574
    }
575
576
    /**
577
     * Form configuration function
578
     *
579
     * @param array $settings
580
     *
581
     * @return string
582
     */
583
    private function renderForm(array $settings)
584
    {
585
        $helper = new HelperForm();
0 ignored issues
show
Bug introduced by
The type HelperForm was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
586
        $helper->show_toolbar = false;
587
        $helper->table = $this->table;
588
        $helper->module = $this;
589
        $helper->default_form_language = $this->context->language->id;
590
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
591
        $helper->identifier = $this->identifier;
592
        $helper->submit_action = 'submit'.$this->name;
593
        $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
0 ignored issues
show
Bug introduced by
The type AdminController was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
594
        $helper->token = Tools::getAdminTokenLite('AdminModules');
595
        $helper->tpl_vars = array(
596
            'fields_value' => $settings,
597
            'languages' => $this->context->controller->getLanguages(),
598
            'id_language' => $this->context->language->id,
599
        );
600
601
        $helper->fields_value['url_ok'] = Configuration::get('url_ok');
602
603
        return $helper->generateForm(array($this->getConfigForm()));
604
    }
605
606
    /**
607
     * Function to update the variables of Pagantis Module in the backoffice of prestashop
608
     *
609
     * @return string
610
     * @throws SmartyException
611
     */
612
    public function getContent()
613
    {
614
        $error = '';
615
        $message = '';
616
        $settings = array();
617
        $settingsKeys = array();
618
        $products = explode(',', Pagantis::getExtraConfig('PRODUCTS', null));
619
        foreach ($products as $product) {
620
            $code = Tools::strtolower(Pagantis::getExtraConfig('CODE', $product));
621
            $settings[$code . '_public_key'] = Configuration::get($code . '_public_key');
622
            $settings[$code . '_private_key'] = Configuration::get($code . '_private_key');
623
            $settings[$code . '_is_enabled'] = Configuration::get($code . '_is_enabled');
624
            if ($code !== 'p4x') {
625
                $settings[$code . '_simulator_is_enabled'] = Configuration::get($code . '_simulator_is_enabled');
626
            }
627
            $settingsKeys[] = $code . '_is_enabled';
628
            $settingsKeys[] = $code . '_public_key';
629
            $settingsKeys[] = $code . '_private_key';
630
            if ($code !== 'p4x') {
631
                $settingsKeys[] = $code . '_simulator_is_enabled';
632
            }
633
        }
634
635
        //Different Behavior depending on 1.6 or earlier
636
        if (Tools::isSubmit('submit'.$this->name)) {
637
            foreach ($settingsKeys as $key) {
638
                $value = Tools::getValue($key);
639
                Configuration::updateValue($key, $value);
640
                $settings[$key] = $value;
641
            }
642
            $message = $this->displayConfirmation($this->l('All changes have been saved'));
643
        } else {
644
            foreach ($settingsKeys as $key) {
645
                    $settings[$key] = Configuration::get($key);
646
            }
647
        }
648
        if ($error) {
649
            $message = $this->displayError($error);
650
        }
651
652
        $logo = 'https://cdn.digitalorigin.com/assets/master/logos/pg.png';
653
        $tpl = $this->local_path.'views/templates/admin/config-info.tpl';
654
        $this->context->smarty->assign(array(
655
            'logo' => $logo,
656
            'form' => $this->renderForm($settings),
657
            'message' => $message,
658
            'version' => 'v'.$this->version,
659
        ));
660
661
        return $this->context->smarty->fetch($tpl);
662
    }
663
664
    /**
665
     * Hook to show payment method, this only applies on prestashop <= 1.6
666
     *
667
     * @param $params
668
     * @return bool | string
669
     * @throws Exception
670
     */
671
    public function hookPayment($params)
672
    {
673
        /** @var Cart $cart */
674
        $cart = $this->context->cart;
675
        $this->shippingAddress = new Address($cart->id_address_delivery);
0 ignored issues
show
Documentation Bug introduced by
It seems like new Address($cart->id_address_delivery) of type Address is incompatible with the declared type null of property $shippingAddress.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
676
        $this->billingAddress = new Address($cart->id_address_invoice);
0 ignored issues
show
Documentation Bug introduced by
It seems like new Address($cart->id_address_invoice) of type Address is incompatible with the declared type null of property $billingAddress.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
677
678
        $orderTotal = $cart->getOrderTotal();
679
        $promotedAmount = 0;
680
        $link = $this->context->link;
681
        $items = $cart->getProducts(true);
682
        foreach ($items as $item) {
683
            $itemCategories = ProductCore::getProductCategoriesFull($item['id_product']);
684
            if (in_array(PROMOTIONS_CATEGORY_NAME, $this->arrayColumn($itemCategories, 'name')) !== false) {
685
                $productId = $item['id_product'];
686
                $promotedAmount += Product::getPriceStatic($productId);
687
            }
688
        }
689
690
        $supercheckout_enabled = Module::isEnabled('supercheckout');
691
        $onepagecheckoutps_enabled = Module::isEnabled('onepagecheckoutps');
692
        $onepagecheckout_enabled = Module::isEnabled('onepagecheckout');
693
694
        $return = '';
695
        $this->context->smarty->assign($this->getButtonTemplateVars($cart));
696
        $products = explode(',', Pagantis::getExtraConfig('PRODUCTS', null));
697
        $templateConfigs = array();
698
        foreach ($products as $product) {
699
            if ($this->isPaymentMethodAvailable($product)) {
700
                $productConfigs = Pagantis::getExtraConfig($product, null);
701
                $productConfigs = json_decode($productConfigs, true);
702
                $publicKey = Configuration::get(Tools::strtolower($productConfigs['CODE']) . '_public_key');
703
                $simulatorIsEnabled = Configuration::get(Tools::strtolower($productConfigs['CODE']) . '_simulator_is_enabled');
704
                $isEnabled = Configuration::get(Tools::strtolower($productConfigs['CODE']) . '_is_enabled');
705
706
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_TITLE'] = $this->l($productConfigs['TITLE']);
707
                unset($productConfigs['TITLE']);
708
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_AMOUNT'] = $orderTotal;
709
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_PROMOTED_AMOUNT'] = $promotedAmount;
710
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_LOCALE'] = $this->language;
711
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_COUNTRY'] = $this->language;
712
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_PUBLIC_KEY'] = $publicKey;
713
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_SIMULATOR_IS_ENABLED'] = $simulatorIsEnabled;
714
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_IS_ENABLED'] = $isEnabled;
715
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_LOGO'] = 'https://cdn.digitalorigin.com/assets/master/logos/pg-favicon.png';
716
                $uri = $link->getModuleLink('pagantis', 'payment');
717
                if (strpos($uri, '?') !== false) {
718
                    $uri .= '&product=' . $productConfigs['CODE'];
719
                } else {
720
                    $uri .= '?product=' . $productConfigs['CODE'];
721
                }
722
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_PAYMENT_URL'] = $uri;
723
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_PS_VERSION'] = str_replace('.', '-', Tools::substr(_PS_VERSION_, 0, 3));
0 ignored issues
show
Bug introduced by
The constant _PS_VERSION_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
724
725
                foreach ($productConfigs as $productConfigKey => $productConfigValue) {
726
                    $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . "_" . $productConfigKey] = $productConfigValue;
727
                }
728
                $this->context->smarty->assign($templateConfigs);
729
                if ($supercheckout_enabled || $onepagecheckout_enabled || $onepagecheckoutps_enabled) {
730
                    $this->checkLogoExists();
731
                    $return .= $this->display(
732
                        __FILE__,
733
                        'views/templates/hook/onepagecheckout-' . Tools::strtolower($productConfigs['CODE']) . '.tpl'
734
                    );
735
                } elseif (_PS_VERSION_ < 1.7) {
736
                    $return .= $this->display(
737
                        __FILE__,
738
                        'views/templates/hook/checkout-' . Tools::strtolower($productConfigs['CODE']) . '.tpl'
739
                    );
740
                }
741
            }
742
        }
743
744
        return $return;
745
    }
746
747
    /**
748
     * @param string $hookName
749
     * @return bool|string
750
     */
751
    public function productPageSimulatorDisplay($hookName = '')
752
    {
753
        $productId = Tools::getValue('id_product');
754
        if (!$productId) {
755
            return false;
756
        }
757
        //Resolves bug of reference passtrow
758
        $amount = Product::getPriceStatic($productId);
759
        $allowedCountries = unserialize(Pagantis::getExtraConfig('ALLOWED_COUNTRIES', null));
760
761
        $itemCategoriesNames = $this->arrayColumn(Product::getProductCategoriesFull($productId), 'name');
762
        $isPromotedProduct = in_array(PROMOTIONS_CATEGORY_NAME, $itemCategoriesNames);
763
764
        $return = '';
765
        $products = explode(',', Pagantis::getExtraConfig('PRODUCTS', null));
766
        $templateConfigs = array();
767
        foreach ($products as $product) {
768
            $productConfigs = Pagantis::getExtraConfig($product, null);
769
            $productConfigs = json_decode($productConfigs, true);
770
771
            $publicKey = Configuration::get(Tools::strtolower($productConfigs['CODE']) . '_public_key');
772
            $simulatorIsEnabled = Configuration::get(Tools::strtolower($productConfigs['CODE']) . '_simulator_is_enabled');
773
            if (Tools::strtolower($productConfigs['CODE']) === 'p4x') {
774
                $simulatorIsEnabled = true;
775
            }
776
            $isEnabled = Configuration::get(Tools::strtolower($productConfigs['CODE']) . '_is_enabled');
777
            $availableSimulators = array(
778
                'hookDisplayProductButtons' => array(
779
                    'sdk.simulator.types.SIMPLE',
780
                    'sdk.simulator.types.SELECTABLE',
781
                    'sdk.simulator.types.MARKETING',
782
                    'sdk.simulator.types.TEXT'
783
                ),
784
                'hookDisplayProductPriceBlock' => array(
785
                    'sdk.simulator.types.PRODUCT_PAGE',
786
                    'sdk.simulator.types.SELECTABLE_TEXT_CUSTOM',
787
                    'p4x',
788
                )
789
            );
790
            if ($isEnabled &&
791
                $simulatorIsEnabled &&
792
                $amount > 0 &&
793
                $amount > $productConfigs['DISPLAY_MIN_AMOUNT'] &&
794
                ($amount < $productConfigs['DISPLAY_MAX_AMOUNT'] || $productConfigs['DISPLAY_MAX_AMOUNT'] === '0') &&
795
                ($amount < $productConfigs['SIMULATOR_DISPLAY_MAX_AMOUNT'] || $productConfigs['SIMULATOR_DISPLAY_MAX_AMOUNT'] === '0') &&
796
                in_array(Tools::strtolower($this->language), $allowedCountries) &&
797
                (in_array($productConfigs['SIMULATOR_DISPLAY_TYPE'], $availableSimulators[$hookName]) || _PS_VERSION_ < 1.6)
0 ignored issues
show
Bug introduced by
The constant _PS_VERSION_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
798
            ) {
799
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_TITLE'] = $this->l($productConfigs['TITLE']);
800
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_SIMULATOR_TITLE'] = $this->l($productConfigs['SIMULATOR_TITLE']);
801
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_SIMULATOR_SUBTITLE'] = $this->l($productConfigs['SIMULATOR_SUBTITLE']);
802
                unset($productConfigs['TITLE']);
803
                unset($productConfigs['SIMULATOR_TITLE']);
804
                unset($productConfigs['SIMULATOR_SUBTITLE']);
805
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_AMOUNT'] = $amount;
806
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_AMOUNT4X'] = number_format(($amount / 4), 2, '.', '');
807
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_IS_PROMOTED_PRODUCT'] = $isPromotedProduct;
808
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_LOCALE'] = $this->language;
809
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_COUNTRY'] = $this->language;
810
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_PUBLIC_KEY'] = $publicKey;
811
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_SIMULATOR_IS_ENABLED'] = $simulatorIsEnabled;
812
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_IS_ENABLED'] = $isEnabled;
813
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_LOGO'] = 'https://cdn.digitalorigin.com/assets/master/logos/pg-favicon.png';
814
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_PS_VERSION'] = str_replace('.', '-', Tools::substr(_PS_VERSION_, 0, 3));
815
                foreach ($productConfigs as $productConfigKey => $productConfigValue) {
816
                    $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . "_" . $productConfigKey] = $productConfigValue;
817
                }
818
819
                $this->context->smarty->assign($templateConfigs);
820
                $return .= $this->display(
821
                    __FILE__,
822
                    'views/templates/hook/product-simulator-' . Tools::strtolower($productConfigs['CODE']) . '.tpl'
823
                );
824
            }
825
        }
826
827
        return $return;
828
    }
829
830
    /**
831
     * @return string
832
     * @throws PrestaShopDatabaseException
833
     * @throws PrestaShopException
834
     */
835
    public function hookDisplayProductButtons()
836
    {
837
        return $this->productPageSimulatorDisplay("hookDisplayProductButtons");
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->productPag...DisplayProductButtons') could also return false which is incompatible with the documented return type string. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
838
    }
839
840
    /**
841
     * @param $params
842
     * @return string
843
     * @throws PrestaShopDatabaseException
844
     * @throws PrestaShopException
845
     */
846
    public function hookDisplayProductPriceBlock($params)
847
    {
848
        // $params['type'] = weight | price | after_price
849
        if (isset($params['type']) && $params['type'] === 'price' &&
850
            isset($params['smarty']) && isset($params['smarty']->template_resource) &&
851
            (strpos($params['smarty']->template_resource, 'product.tpl') !== false  ||
852
            strpos($params['smarty']->template_resource, 'product-prices.tpl') !== false)
853
        ) {
854
            return $this->productPageSimulatorDisplay("hookDisplayProductPriceBlock");
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->productPag...playProductPriceBlock') could also return false which is incompatible with the documented return type string. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
855
        }
856
        return '';
857
    }
858
859
    /**
860
     * @param array $params
861
     *
862
     * @return string
863
     */
864
    public function hookDisplayOrderConfirmation($params)
865
    {
866
        $paymentMethod = (_PS_VERSION_ < 1.7) ? ($params["objOrder"]->payment) : ($params["order"]->payment);
0 ignored issues
show
Bug introduced by
The constant _PS_VERSION_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
867
868
        if ($paymentMethod == $this->displayName) {
869
            return $this->display(__FILE__, 'views/templates/hook/payment-return.tpl');
870
        }
871
872
        return null;
873
    }
874
875
    /**
876
     * checkPromotionCategory
877
     */
878
    public function checkPromotionCategory()
879
    {
880
        $categories = $this->arrayColumn(Category::getCategories(null, false, false), 'name');
0 ignored issues
show
Bug introduced by
The type Category was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
881
        if (!in_array(PROMOTIONS_CATEGORY_NAME, $categories)) {
882
            /** @var CategoryCore $category */
883
            $category = new Category();
884
            $categoryArray = array((int)Configuration::get('PS_LANG_DEFAULT')=> PROMOTIONS_CATEGORY );
885
            $category->is_root_category = false;
886
            $category->link_rewrite = $categoryArray;
887
            $category->meta_description = $categoryArray;
888
            $category->meta_keywords = $categoryArray;
889
            $category->meta_title = $categoryArray;
890
            $category->name = array((int)Configuration::get('PS_LANG_DEFAULT')=> PROMOTIONS_CATEGORY_NAME);
891
            $category->id_parent = Configuration::get('PS_HOME_CATEGORY');
892
            $category->active=0;
893
            $description = 'Pagantis: Products with this category have free financing assumed by the merchant. ' .
894
                'Use it to promote your products or brands.';
895
            $category->description = $this->l($description);
896
            $category->save();
897
        }
898
    }
899
900
    /**
901
     * @param null   $config
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $config is correct as it would always require null to be passed?
Loading history...
902
     * @param        $product
903
     * @param string $default
904
     * @return string
905
     */
906
    public static function getExtraConfig($config = null, $product = "P4X", $default = '')
907
    {
908
        if (is_null($config)) {
0 ignored issues
show
introduced by
The condition is_null($config) is always true.
Loading history...
909
            return '';
910
        }
911
912
        if (is_null($product)) {
913
            $sql = 'SELECT value FROM '._DB_PREFIX_.'pagantis_config where config = \'' . pSQL($config) . '\' limit 1';
0 ignored issues
show
Bug introduced by
The function pSQL 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

913
            $sql = 'SELECT value FROM '._DB_PREFIX_.'pagantis_config where config = \'' . /** @scrutinizer ignore-call */ pSQL($config) . '\' limit 1';
Loading history...
Bug introduced by
The constant _DB_PREFIX_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
914
            if ($results = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql)) {
0 ignored issues
show
Bug introduced by
The constant _PS_USE_SQL_SLAVE_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
915
                if (is_array($results) && count($results) === 1 && isset($results[0]['value'])) {
916
                    return $results[0]['value'];
917
                }
918
            }
919
        }
920
921
        $sql = 'SELECT value FROM '._DB_PREFIX_.'pagantis_config where config = \'' . pSQL($product) . '\' limit 1';
922
        if ($results = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql)) {
923
            if (is_array($results) && count($results) === 1 && isset($results[0]['value'])) {
924
                $configs = json_decode($results[0]['value'], true);
925
                $value = '';
926
                if (isset($configs[$config])) {
927
                    $value = $configs[$config];
928
                }
929
                return $value;
930
            }
931
        }
932
933
        return $default;
934
    }
935
936
    /**
937
     * Check logo exists in OPC module
938
     */
939
    public function checkLogoExists()
940
    {
941
        $logoPg = _PS_MODULE_DIR_ . '/onepagecheckoutps/views/img/payments/pagantis.png';
0 ignored issues
show
Bug introduced by
The constant _PS_MODULE_DIR_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
942
        if (!file_exists($logoPg) && is_dir(_PS_MODULE_DIR_ . '/onepagecheckoutps/views/img/payments')) {
943
            copy(
944
                _PS_PAGANTIS_DIR . '/logo.png',
945
                $logoPg
946
            );
947
        }
948
    }
949
950
    /**
951
     * Get user language
952
     */
953
    private function getUserLanguage()
954
    {
955
        $lang = Language::getLanguage($this->context->language->id);
0 ignored issues
show
Bug introduced by
The type Language was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
956
        $langArray = explode("-", $lang['language_code']);
957
        if (count($langArray) != 2 && isset($lang['locale'])) {
958
            $langArray = explode("-", $lang['locale']);
959
        }
960
        $this->language = Tools::strtoupper($langArray[count($langArray)-1]);
961
        // Prevent null language detection
962
        if (in_array(Tools::strtolower($this->language), $this->allowedCountries)) {
963
            return;
964
        }
965
        if ($this->shippingAddress) {
966
            $this->language = Country::getIsoById($this->shippingAddress->id_country);
0 ignored issues
show
Bug introduced by
The type Country was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
967
            if (in_array(Tools::strtolower($this->language), $this->allowedCountries)) {
968
                return;
969
            }
970
        }
971
        if ($this->billingAddress) {
972
            $this->language = Country::getIsoById($this->billingAddress->id_country);
973
            if (in_array(Tools::strtolower($this->language), $this->allowedCountries)) {
974
                return;
975
            }
976
        }
977
        return $this->language;
978
    }
979
980
    /**
981
     * @param array $input
982
     * @param       $columnKey
983
     * @param null  $indexKey
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $indexKey is correct as it would always require null to be passed?
Loading history...
984
     *
985
     * @return array|bool
986
     */
987
    private function arrayColumn(array $input, $columnKey, $indexKey = null)
988
    {
989
        $array = array();
990
        foreach ($input as $value) {
991
            if (!array_key_exists($columnKey, $value)) {
992
                trigger_error("Key \"$columnKey\" does not exist in array");
993
                return false;
994
            }
995
            if (is_null($indexKey)) {
996
                $array[] = $value[$columnKey];
997
            } else {
998
                if (!array_key_exists($indexKey, $value)) {
999
                    trigger_error("Key \"$indexKey\" does not exist in array");
1000
                    return false;
1001
                }
1002
                if (!is_scalar($value[$indexKey])) {
1003
                    trigger_error("Key \"$indexKey\" does not contain scalar value");
1004
                    return false;
1005
                }
1006
                $array[$value[$indexKey]] = $value[$columnKey];
1007
            }
1008
        }
1009
        return $array;
1010
    }
1011
}
1012