Completed
Push — master ( 5b4212...59ab2a )
by Raúl
18s queued 11s
created

Pagantis::loadSQLFile()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 3
eloc 8
c 4
b 0
f 0
nc 3
nop 1
dl 0
loc 14
rs 10
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 = "DROP TABLE $tableName";
322
                    Db::getInstance()->Execute($sql);
323
                    $sql_file = dirname(__FILE__).'/sql/install.sql';
324
                    $this->loadSQLFile($sql_file);
325
                }
326
            } else {
327
                $sql_file = dirname(__FILE__).'/sql/install.sql';
328
                $this->loadSQLFile($sql_file);
329
            }
330
            $tableName = _DB_PREFIX_.'pagantis_config';
331
            $sql = "show tables like '"   . $tableName . "'";
332
            $data = Db::getInstance()->ExecuteS($sql);
333
            if (count($data) > 0) {
334
                $sql = "desc "   . $tableName;
335
                $data = Db::getInstance()->ExecuteS($sql);
336
                if (count($data) === 3 && $data[2]['Type'] !== 'varchar(5000)') {
337
                    $sql = "ALTER TABLE $tableName MODIFY `value` VARCHAR(5000)";
338
                    Db::getInstance()->Execute($sql);
339
                }
340
                // return because pagantis tables exisit so load the sqlfile is not needed
341
            }
342
        } catch (\Exception $exception) {
343
            // do nothing
344
        }
345
    }
346
347
    /**
348
     * Check amount of order > minAmount
349
     * Check valid currency
350
     * Check API variables are set
351
     *
352
     * @param string $product
353
     * @return bool
354
     */
355
    public function isPaymentMethodAvailable($product = 'p4x')
356
    {
357
        $configs = json_decode(Pagantis::getExtraConfig($product, null), true);
358
        $cart                      = $this->context->cart;
359
        $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...
360
        $availableCurrencies       = array('EUR');
361
        $pagantisDisplayMinAmount  = $configs['DISPLAY_MIN_AMOUNT'];
362
        $pagantisDisplayMaxAmount  = $configs['DISPLAY_MAX_AMOUNT'];
363
        $pagantisPublicKey         = Configuration::get(Tools::strtolower($configs['CODE']) . '_public_key');
364
        $pagantisPrivateKey        = Configuration::get(Tools::strtolower($configs['CODE']) . '_private_key');
365
        $this->allowedCountries    = unserialize(Pagantis::getExtraConfig('ALLOWED_COUNTRIES', null));
366
        $this->getUserLanguage();
367
        return (
368
            $cart->getOrderTotal() >= $pagantisDisplayMinAmount &&
369
            ($cart->getOrderTotal() <= $pagantisDisplayMaxAmount || $pagantisDisplayMaxAmount == '0') &&
370
            in_array($currency->iso_code, $availableCurrencies) &&
371
            in_array(Tools::strtolower($this->language), $this->allowedCountries) &&
372
            $pagantisPublicKey &&
373
            $pagantisPrivateKey
374
        );
375
    }
376
377
    /**
378
     * @param Cart $cart
379
     *
380
     * @return array
381
     * @throws Exception
382
     */
383
    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...
384
    {
385
        $currency = new Currency(($cart->id_currency));
386
387
        return array(
388
            'button' => '#payment_button',
389
            'currency_iso' => $currency->iso_code,
390
            'cart_total' => $cart->getOrderTotal(),
391
        );
392
    }
393
394
    /**
395
     * Header hook
396
     */
397
    public function hookHeader()
398
    {
399
400
        $url = 'https://cdn.pagantis.com/js/pg-v2/sdk.js';
401
        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...
402
            $this->context->controller->registerJavascript(
403
                sha1(mt_rand(1, 90000)),
404
                $url,
405
                array('server' => 'remote')
406
            );
407
        } else {
408
            $this->context->controller->addJS($url);
409
        }
410
    }
411
412
    /**
413
     * @return array
414
     * @throws Exception
415
     */
416
    public function hookPaymentOptions()
417
    {
418
        /** @var Cart $cart */
419
        $cart = $this->context->cart;
420
        $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...
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...
421
        $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...
422
423
        $orderTotal = $cart->getOrderTotal();
424
        $promotedAmount = 0;
425
        $link = $this->context->link;
426
        $items = $cart->getProducts(true);
427
        foreach ($items as $item) {
428
            $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...
429
            if (in_array(PROMOTIONS_CATEGORY_NAME, $this->arrayColumn($itemCategories, 'name')) !== false) {
430
                $productId = $item['id_product'];
431
                $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...
432
            }
433
        }
434
435
        $return = array();
436
        $this->context->smarty->assign($this->getButtonTemplateVars($cart));
437
        $products = explode(',', Pagantis::getExtraConfig('PRODUCTS', null));
438
        $templateConfigs = array();
439
        foreach ($products as $product) {
440
            if ($this->isPaymentMethodAvailable($product)) {
441
                $productConfigs = Pagantis::getExtraConfig($product, null);
442
                $productConfigs = json_decode($productConfigs, true);
443
                $publicKey = Configuration::get(Tools::strtolower($productConfigs['CODE']) . '_public_key');
444
                $simulatorIsEnabled = Configuration::get(Tools::strtolower($productConfigs['CODE']) . '_simulator_is_enabled');
445
                $isEnabled = Configuration::get(Tools::strtolower($productConfigs['CODE']) . '_is_enabled');
446
447
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_TITLE'] = $this->l($productConfigs['TITLE']);
448
                unset($productConfigs['TITLE']);
449
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_AMOUNT'] = $orderTotal;
450
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_PROMOTED_AMOUNT'] = $promotedAmount;
451
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_LOCALE'] = $this->language;
452
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_COUNTRY'] = $this->language;
453
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_PUBLIC_KEY'] = $publicKey;
454
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_SIMULATOR_IS_ENABLED'] = $simulatorIsEnabled;
455
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_IS_ENABLED'] = $isEnabled;
456
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_LOGO'] = 'https://cdn.digitalorigin.com/assets/master/logos/pg-favicon.png';
457
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_PAYMENT_URL'] = $link->getModuleLink('pagantis', 'payment') . '&product=' . $productConfigs['CODE'];
458
                $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...
459
460
                foreach ($productConfigs as $productConfigKey => $productConfigValue) {
461
                    $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . "_" . $productConfigKey] = $productConfigValue;
462
                }
463
                $this->context->smarty->assign($templateConfigs);
464
465
                $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...
466
                $uri = $link->getModuleLink('pagantis', 'payment');
467
                if (strpos($uri, '?') !== false) {
468
                    $uri .= '&product=' . $productConfigs['CODE'];
469
                } else {
470
                    $uri .= '?product=' . $productConfigs['CODE'];
471
                }
472
                $paymentOption
473
                    ->setCallToActionText($templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_TITLE'])
474
                    ->setAction($uri)
475
                    ->setLogo($templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_LOGO'])
476
                    ->setModuleName(__CLASS__)
477
                    ->setAdditionalInformation(
478
                        $this->fetch('module:pagantis/views/templates/hook/checkout-' . Tools::strtolower($productConfigs['CODE']) . '.tpl')
479
                    )
480
                ;
481
                $return[] = $paymentOption;
482
            }
483
        }
484
        if (count($return) === 0) {
485
            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...
486
        }
487
        return $return;
488
    }
489
490
    /**
491
     * Get the form for editing the BackOffice options of the module
492
     *
493
     * @return array
494
            */
495
    private function getConfigForm()
496
    {
497
        $products = explode(',', Pagantis::getExtraConfig('PRODUCTS', null));
498
        $inputs = array();
499
        foreach ($products as $product) {
500
            $code = Tools::strtolower(Pagantis::getExtraConfig('CODE', $product));
501
            $inputs[] = array(
502
                'name' => $code .'_is_enabled',
503
                '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...
504
                'label' => $this->l('Module is enabled ' . $code),
505
                'prefix' => '<i class="icon icon-key"></i>',
506
                'class' => 't',
507
                'required' => true,
508
                'values'=> array(
509
                    array(
510
                        'id' => $code .'_is_enabled_true',
511
                        'value' => 1,
512
                        'label' => $this->l('Yes', get_class($this), null, false),
513
                    ),
514
                    array(
515
                        'id' => $code . '_is_enabled_false',
516
                        'value' => 0,
517
                        'label' => $this->l('No', get_class($this), null, false),
518
                    ),
519
                )
520
            );
521
            $inputs[] = array(
522
                'name' => $code . '_public_key',
523
                'suffix' => $this->l('ex: pk_fd53cd467ba49022e4gf215e'),
524
                'type' => 'text',
525
                'size' => 60,
526
                'label' => $this->l('Public Key ' . $code),
527
                'prefix' => '<i class="icon icon-key"></i>',
528
                'col' => 6,
529
                'required' => true,
530
            );
531
            $inputs[] = array(
532
                'name' => $code . '_private_key',
533
                'suffix' => $this->l('ex: 21e5723a97459f6a'),
534
                'type' => 'text',
535
                'size' => 60,
536
                'label' => $this->l('Private Key ' . $code),
537
                'prefix' => '<i class="icon icon-key"></i>',
538
                'col' => 6,
539
                'required' => true,
540
            );
541
            if ($code !== "p4x") {
542
                $inputs[] = array(
543
                    'name' => $code . '_simulator_is_enabled',
544
                    'type' => (version_compare(_PS_VERSION_, '1.6')<0) ?'radio' :'switch',
545
                    'label' => $this->l('Simulator is enabled ' . $code),
546
                    'prefix' => '<i class="icon icon-key"></i>',
547
                    'class' => 't',
548
                    'required' => true,
549
                    'values'=> array(
550
                        array(
551
                            'id' => $code . '_simulator_is_enabled_on',
552
                            'value' => 1,
553
                            'label' => $this->l('Yes'),
554
                        ),
555
                        array(
556
                            'id' => $code . '_simulator_is_enabled_off',
557
                            'value' => 0,
558
                            'label' => $this->l('No'),
559
                        ),
560
                    )
561
                );
562
            }
563
        }
564
        $return = array(
565
            'form' => array(
566
                'legend' => array(
567
                    'title' => $this->l('Basic Settings'),
568
                    'icon' => 'icon-cogs',
569
                ),
570
                'input' => $inputs,
571
                'submit' => array(
572
                    'title' => $this->l('Save'),
573
                )
574
            )
575
        );
576
        return $return;
577
    }
578
579
    /**
580
     * Form configuration function
581
     *
582
     * @param array $settings
583
     *
584
     * @return string
585
     */
586
    private function renderForm(array $settings)
587
    {
588
        $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...
589
        $helper->show_toolbar = false;
590
        $helper->table = $this->table;
591
        $helper->module = $this;
592
        $helper->default_form_language = $this->context->language->id;
593
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
594
        $helper->identifier = $this->identifier;
595
        $helper->submit_action = 'submit'.$this->name;
596
        $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...
597
        $helper->token = Tools::getAdminTokenLite('AdminModules');
598
        $helper->tpl_vars = array(
599
            'fields_value' => $settings,
600
            'languages' => $this->context->controller->getLanguages(),
601
            'id_language' => $this->context->language->id,
602
        );
603
604
        $helper->fields_value['url_ok'] = Configuration::get('url_ok');
605
606
        return $helper->generateForm(array($this->getConfigForm()));
607
    }
608
609
    /**
610
     * Function to update the variables of Pagantis Module in the backoffice of prestashop
611
     *
612
     * @return string
613
     * @throws SmartyException
614
     */
615
    public function getContent()
616
    {
617
        $error = '';
618
        $message = '';
619
        $settings = array();
620
        $settingsKeys = array();
621
        $products = explode(',', Pagantis::getExtraConfig('PRODUCTS', null));
622
        foreach ($products as $product) {
623
            $code = Tools::strtolower(Pagantis::getExtraConfig('CODE', $product));
624
            $settings[$code . '_public_key'] = Configuration::get($code . '_public_key');
625
            $settings[$code . '_private_key'] = Configuration::get($code . '_private_key');
626
            $settings[$code . '_is_enabled'] = Configuration::get($code . '_is_enabled');
627
            if ($code !== 'p4x') {
628
                $settings[$code . '_simulator_is_enabled'] = Configuration::get($code . '_simulator_is_enabled');
629
            }
630
            $settingsKeys[] = $code . '_is_enabled';
631
            $settingsKeys[] = $code . '_public_key';
632
            $settingsKeys[] = $code . '_private_key';
633
            if ($code !== 'p4x') {
634
                $settingsKeys[] = $code . '_simulator_is_enabled';
635
            }
636
        }
637
638
        //Different Behavior depending on 1.6 or earlier
639
        if (Tools::isSubmit('submit'.$this->name)) {
640
            foreach ($settingsKeys as $key) {
641
                $value = Tools::getValue($key);
642
                Configuration::updateValue($key, $value);
643
                $settings[$key] = $value;
644
            }
645
            $message = $this->displayConfirmation($this->l('All changes have been saved'));
646
        } else {
647
            foreach ($settingsKeys as $key) {
648
                    $settings[$key] = Configuration::get($key);
649
            }
650
        }
651
        if ($error) {
652
            $message = $this->displayError($error);
653
        }
654
655
        $logo = 'https://cdn.digitalorigin.com/assets/master/logos/pg.png';
656
        $tpl = $this->local_path.'views/templates/admin/config-info.tpl';
657
        $this->context->smarty->assign(array(
658
            'logo' => $logo,
659
            'form' => $this->renderForm($settings),
660
            'message' => $message,
661
            'version' => 'v'.$this->version,
662
        ));
663
664
        return $this->context->smarty->fetch($tpl);
665
    }
666
667
    /**
668
     * Hook to show payment method, this only applies on prestashop <= 1.6
669
     *
670
     * @param $params
671
     * @return bool | string
672
     * @throws Exception
673
     */
674
    public function hookPayment($params)
675
    {
676
        /** @var Cart $cart */
677
        $cart = $this->context->cart;
678
        $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...
679
        $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...
680
681
        $orderTotal = $cart->getOrderTotal();
682
        $promotedAmount = 0;
683
        $link = $this->context->link;
684
        $items = $cart->getProducts(true);
685
        foreach ($items as $item) {
686
            $itemCategories = ProductCore::getProductCategoriesFull($item['id_product']);
687
            if (in_array(PROMOTIONS_CATEGORY_NAME, $this->arrayColumn($itemCategories, 'name')) !== false) {
688
                $productId = $item['id_product'];
689
                $promotedAmount += Product::getPriceStatic($productId);
690
            }
691
        }
692
693
        $supercheckout_enabled = Module::isEnabled('supercheckout');
694
        $onepagecheckoutps_enabled = Module::isEnabled('onepagecheckoutps');
695
        $onepagecheckout_enabled = Module::isEnabled('onepagecheckout');
696
697
        $return = '';
698
        $this->context->smarty->assign($this->getButtonTemplateVars($cart));
699
        $products = explode(',', Pagantis::getExtraConfig('PRODUCTS', null));
700
        $templateConfigs = array();
701
        foreach ($products as $product) {
702
            if ($this->isPaymentMethodAvailable($product)) {
703
                $productConfigs = Pagantis::getExtraConfig($product, null);
704
                $productConfigs = json_decode($productConfigs, true);
705
                $publicKey = Configuration::get(Tools::strtolower($productConfigs['CODE']) . '_public_key');
706
                $simulatorIsEnabled = Configuration::get(Tools::strtolower($productConfigs['CODE']) . '_simulator_is_enabled');
707
                $isEnabled = Configuration::get(Tools::strtolower($productConfigs['CODE']) . '_is_enabled');
708
709
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_TITLE'] = $this->l($productConfigs['TITLE']);
710
                unset($productConfigs['TITLE']);
711
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_AMOUNT'] = $orderTotal;
712
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_PROMOTED_AMOUNT'] = $promotedAmount;
713
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_LOCALE'] = $this->language;
714
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_COUNTRY'] = $this->language;
715
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_PUBLIC_KEY'] = $publicKey;
716
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_SIMULATOR_IS_ENABLED'] = $simulatorIsEnabled;
717
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_IS_ENABLED'] = $isEnabled;
718
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_LOGO'] = 'https://cdn.digitalorigin.com/assets/master/logos/pg-favicon.png';
719
                $uri = $link->getModuleLink('pagantis', 'payment');
720
                if (strpos($uri, '?') !== false) {
721
                    $uri .= '&product=' . $productConfigs['CODE'];
722
                } else {
723
                    $uri .= '?product=' . $productConfigs['CODE'];
724
                }
725
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_PAYMENT_URL'] = $uri;
726
                $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...
727
728
                foreach ($productConfigs as $productConfigKey => $productConfigValue) {
729
                    $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . "_" . $productConfigKey] = $productConfigValue;
730
                }
731
                $this->context->smarty->assign($templateConfigs);
732
                if ($supercheckout_enabled || $onepagecheckout_enabled || $onepagecheckoutps_enabled) {
733
                    $this->checkLogoExists();
734
                    $return .= $this->display(
735
                        __FILE__,
736
                        'views/templates/hook/onepagecheckout-' . Tools::strtolower($productConfigs['CODE']) . '.tpl'
737
                    );
738
                } elseif (_PS_VERSION_ < 1.7) {
739
                    $return .= $this->display(
740
                        __FILE__,
741
                        'views/templates/hook/checkout-' . Tools::strtolower($productConfigs['CODE']) . '.tpl'
742
                    );
743
                }
744
            }
745
        }
746
747
        return $return;
748
    }
749
750
    /**
751
     * @param string $hookName
752
     * @return bool|string
753
     */
754
    public function productPageSimulatorDisplay($hookName = '')
755
    {
756
        $productId = Tools::getValue('id_product');
757
        if (!$productId) {
758
            return false;
759
        }
760
        //Resolves bug of reference passtrow
761
        $amount = Product::getPriceStatic($productId);
762
        $allowedCountries = unserialize(Pagantis::getExtraConfig('ALLOWED_COUNTRIES', null));
763
764
        $itemCategoriesNames = $this->arrayColumn(Product::getProductCategoriesFull($productId), 'name');
765
        $isPromotedProduct = in_array(PROMOTIONS_CATEGORY_NAME, $itemCategoriesNames);
766
767
        $return = '';
768
        $products = explode(',', Pagantis::getExtraConfig('PRODUCTS', null));
769
        $templateConfigs = array();
770
        foreach ($products as $product) {
771
            $productConfigs = Pagantis::getExtraConfig($product, null);
772
            $productConfigs = json_decode($productConfigs, true);
773
774
            $publicKey = Configuration::get(Tools::strtolower($productConfigs['CODE']) . '_public_key');
775
            $simulatorIsEnabled = Configuration::get(Tools::strtolower($productConfigs['CODE']) . '_simulator_is_enabled');
776
            if (Tools::strtolower($productConfigs['CODE']) === 'p4x') {
777
                $simulatorIsEnabled = true;
778
            }
779
            $isEnabled = Configuration::get(Tools::strtolower($productConfigs['CODE']) . '_is_enabled');
780
            $availableSimulators = array(
781
                'hookDisplayProductButtons' => array(
782
                    'sdk.simulator.types.SIMPLE',
783
                    'sdk.simulator.types.SELECTABLE',
784
                    'sdk.simulator.types.MARKETING',
785
                    'sdk.simulator.types.TEXT'
786
                ),
787
                'hookDisplayProductPriceBlock' => array(
788
                    'sdk.simulator.types.PRODUCT_PAGE',
789
                    'sdk.simulator.types.SELECTABLE_TEXT_CUSTOM',
790
                    'p4x',
791
                )
792
            );
793
            if ($isEnabled &&
794
                $simulatorIsEnabled &&
795
                $amount > 0 &&
796
                $amount > $productConfigs['DISPLAY_MIN_AMOUNT'] &&
797
                ($amount < $productConfigs['DISPLAY_MAX_AMOUNT'] || $productConfigs['DISPLAY_MAX_AMOUNT'] === '0') &&
798
                ($amount < $productConfigs['SIMULATOR_DISPLAY_MAX_AMOUNT'] || $productConfigs['SIMULATOR_DISPLAY_MAX_AMOUNT'] === '0') &&
799
                in_array(Tools::strtolower($this->language), $allowedCountries) &&
800
                (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...
801
            ) {
802
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_TITLE'] = $this->l($productConfigs['TITLE']);
803
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_SIMULATOR_TITLE'] = $this->l($productConfigs['SIMULATOR_TITLE']);
804
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_SIMULATOR_SUBTITLE'] = $this->l($productConfigs['SIMULATOR_SUBTITLE']);
805
                unset($productConfigs['TITLE']);
806
                unset($productConfigs['SIMULATOR_TITLE']);
807
                unset($productConfigs['SIMULATOR_SUBTITLE']);
808
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_AMOUNT'] = $amount;
809
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_AMOUNT4X'] = number_format(($amount / 4), 2, '.', '');
810
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_IS_PROMOTED_PRODUCT'] = $isPromotedProduct;
811
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_LOCALE'] = $this->language;
812
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_COUNTRY'] = $this->language;
813
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_PUBLIC_KEY'] = $publicKey;
814
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_SIMULATOR_IS_ENABLED'] = $simulatorIsEnabled;
815
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_IS_ENABLED'] = $isEnabled;
816
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_LOGO'] = 'https://cdn.digitalorigin.com/assets/master/logos/pg-favicon.png';
817
                $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . '_PS_VERSION'] = str_replace('.', '-', Tools::substr(_PS_VERSION_, 0, 3));
818
                foreach ($productConfigs as $productConfigKey => $productConfigValue) {
819
                    $templateConfigs[Tools::strtoupper(Tools::strtolower($productConfigs['CODE'])) . "_" . $productConfigKey] = $productConfigValue;
820
                }
821
822
                $this->context->smarty->assign($templateConfigs);
823
                $return .= $this->display(
824
                    __FILE__,
825
                    'views/templates/hook/product-simulator-' . Tools::strtolower($productConfigs['CODE']) . '.tpl'
826
                );
827
            }
828
        }
829
830
        return $return;
831
    }
832
833
    /**
834
     * @return string
835
     * @throws PrestaShopDatabaseException
836
     * @throws PrestaShopException
837
     */
838
    public function hookDisplayProductButtons()
839
    {
840
        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...
841
    }
842
843
    /**
844
     * @param $params
845
     * @return string
846
     * @throws PrestaShopDatabaseException
847
     * @throws PrestaShopException
848
     */
849
    public function hookDisplayProductPriceBlock($params)
850
    {
851
        // $params['type'] = weight | price | after_price
852
        if (isset($params['type']) && $params['type'] === 'price' &&
853
            isset($params['smarty']) && isset($params['smarty']->template_resource) &&
854
            (strpos($params['smarty']->template_resource, 'product.tpl') !== false  ||
855
            strpos($params['smarty']->template_resource, 'product-prices.tpl') !== false)
856
        ) {
857
            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...
858
        }
859
        return '';
860
    }
861
862
    /**
863
     * @param array $params
864
     *
865
     * @return string
866
     */
867
    public function hookDisplayOrderConfirmation($params)
868
    {
869
        $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...
870
871
        if ($paymentMethod == $this->displayName) {
872
            return $this->display(__FILE__, 'views/templates/hook/payment-return.tpl');
873
        }
874
875
        return null;
876
    }
877
878
    /**
879
     * checkPromotionCategory
880
     */
881
    public function checkPromotionCategory()
882
    {
883
        $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...
884
        if (!in_array(PROMOTIONS_CATEGORY_NAME, $categories)) {
885
            /** @var CategoryCore $category */
886
            $category = new Category();
887
            $categoryArray = array((int)Configuration::get('PS_LANG_DEFAULT')=> PROMOTIONS_CATEGORY );
888
            $category->is_root_category = false;
889
            $category->link_rewrite = $categoryArray;
890
            $category->meta_description = $categoryArray;
891
            $category->meta_keywords = $categoryArray;
892
            $category->meta_title = $categoryArray;
893
            $category->name = array((int)Configuration::get('PS_LANG_DEFAULT')=> PROMOTIONS_CATEGORY_NAME);
894
            $category->id_parent = Configuration::get('PS_HOME_CATEGORY');
895
            $category->active=0;
896
            $description = 'Pagantis: Products with this category have free financing assumed by the merchant. ' .
897
                'Use it to promote your products or brands.';
898
            $category->description = $this->l($description);
899
            $category->save();
900
        }
901
    }
902
903
    /**
904
     * @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...
905
     * @param        $product
906
     * @param string $default
907
     * @return string
908
     */
909
    public static function getExtraConfig($config = null, $product = "P4X", $default = '')
910
    {
911
        if (is_null($config)) {
0 ignored issues
show
introduced by
The condition is_null($config) is always true.
Loading history...
912
            return '';
913
        }
914
915
        if (is_null($product)) {
916
            $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

916
            $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...
917
            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...
918
                if (is_array($results) && count($results) === 1 && isset($results[0]['value'])) {
919
                    return $results[0]['value'];
920
                }
921
            }
922
        }
923
924
        $sql = 'SELECT value FROM '._DB_PREFIX_.'pagantis_config where config = \'' . pSQL($product) . '\' limit 1';
925
        if ($results = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql)) {
926
            if (is_array($results) && count($results) === 1 && isset($results[0]['value'])) {
927
                $configs = json_decode($results[0]['value'], true);
928
                $value = '';
929
                if (isset($configs[$config])) {
930
                    $value = $configs[$config];
931
                }
932
                return $value;
933
            }
934
        }
935
936
        return $default;
937
    }
938
939
    /**
940
     * Check logo exists in OPC module
941
     */
942
    public function checkLogoExists()
943
    {
944
        $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...
945
        if (!file_exists($logoPg) && is_dir(_PS_MODULE_DIR_ . '/onepagecheckoutps/views/img/payments')) {
946
            copy(
947
                _PS_PAGANTIS_DIR . '/logo.png',
948
                $logoPg
949
            );
950
        }
951
    }
952
953
    /**
954
     * Get user language
955
     */
956
    private function getUserLanguage()
957
    {
958
        $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...
959
        $langArray = explode("-", $lang['language_code']);
960
        if (count($langArray) != 2 && isset($lang['locale'])) {
961
            $langArray = explode("-", $lang['locale']);
962
        }
963
        $this->language = Tools::strtoupper($langArray[count($langArray)-1]);
964
        // Prevent null language detection
965
        if (in_array(Tools::strtolower($this->language), $this->allowedCountries)) {
966
            return;
967
        }
968
        if ($this->shippingAddress) {
969
            $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...
970
            if (in_array(Tools::strtolower($this->language), $this->allowedCountries)) {
971
                return;
972
            }
973
        }
974
        if ($this->billingAddress) {
975
            $this->language = Country::getIsoById($this->billingAddress->id_country);
976
            if (in_array(Tools::strtolower($this->language), $this->allowedCountries)) {
977
                return;
978
            }
979
        }
980
        return $this->language;
981
    }
982
983
    /**
984
     * @param array $input
985
     * @param       $columnKey
986
     * @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...
987
     *
988
     * @return array|bool
989
     */
990
    private function arrayColumn(array $input, $columnKey, $indexKey = null)
991
    {
992
        $array = array();
993
        foreach ($input as $value) {
994
            if (!array_key_exists($columnKey, $value)) {
995
                trigger_error("Key \"$columnKey\" does not exist in array");
996
                return false;
997
            }
998
            if (is_null($indexKey)) {
999
                $array[] = $value[$columnKey];
1000
            } else {
1001
                if (!array_key_exists($indexKey, $value)) {
1002
                    trigger_error("Key \"$indexKey\" does not exist in array");
1003
                    return false;
1004
                }
1005
                if (!is_scalar($value[$indexKey])) {
1006
                    trigger_error("Key \"$indexKey\" does not contain scalar value");
1007
                    return false;
1008
                }
1009
                $array[$value[$indexKey]] = $value[$columnKey];
1010
            }
1011
        }
1012
        return $array;
1013
    }
1014
}
1015