Passed
Pull Request — master (#34)
by Raúl
02:26
created

Pagantis::loadEnvVariables()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 16
nc 8
nop 0
dl 0
loc 27
rs 9.4222
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of the official Pagantis module for PrestaShop.
4
 *
5
 * @author    Pagantis <[email protected]>
6
 * @copyright 2015-2016 Pagantis
7
 * @license   proprietary
8
 */
9
10
if (!defined('_PS_VERSION_')) {
11
    exit;
12
}
13
14
define('_PS_PAYLATER_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
16
require _PS_PAYLATER_DIR.'/vendor/autoload.php';
17
18
/**
19
 * Class Pagantis
20
 */
21
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...
22
{
23
    /**
24
     * @var string
25
     */
26
    public $url = 'https://pagantis.com';
27
28
    /**
29
     * @var bool
30
     */
31
    public $bootstrap = true;
32
33
    /**
34
     * @var array
35
     */
36
    public $installErrors = array();
37
38
    /**
39
     * Default module advanced configuration values
40
     *
41
     * @var array
42
     */
43
    public $defaultConfigs = array(
44
        'PAGANTIS_TITLE' => 'Instant Financing',
45
        'PAGANTIS_SIMULATOR_DISPLAY_TYPE' => 'pmtSDK.simulator.types.SIMPLE',
46
        'PAGANTIS_SIMULATOR_DISPLAY_SKIN' => 'pmtSDK.simulator.skins.BLUE',
47
        'PAGANTIS_SIMULATOR_DISPLAY_POSITION' => 'hookDisplayProductButtons',
48
        'PAGANTIS_SIMULATOR_START_INSTALLMENTS' => '3',
49
        'PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR' => 'default',
50
        'PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION' => 'pmtSDK.simulator.positions.INNER',
51
        'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR' => 'default',
52
        'PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR' => 'default',
53
        'PAGANTIS_FORM_DISPLAY_TYPE' => '0',
54
        'PAGANTIS_DISPLAY_MIN_AMOUNT' => '1',
55
        'PAGANTIS_URL_OK' => '',
56
        'PAGANTIS_URL_KO' => '',
57
    );
58
59
    /**
60
     * Pagantis constructor.
61
     *
62
     * Define the module main properties so that prestashop understands what are the module requirements
63
     * and how to manage the module.
64
     *
65
     */
66
    public function __construct()
67
    {
68
        $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...
69
        $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...
70
        $this->version = '8.0.0';
0 ignored issues
show
Bug Best Practice introduced by
The property version does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
71
        $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...
72
        $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...
73
        $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...
74
        $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...
75
        $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...
76
        $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...
77
        $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...
78
            'Instant, easy and effective financial tool for your customers'
79
        );
80
81
        $sql_file = dirname(__FILE__).'/sql/install.sql';
82
        $this->loadSQLFile($sql_file);
83
84
        $this->loadEnvVariables();
85
86
        $this->migrate();
87
88
        $this->checkHooks();
89
90
        parent::__construct();
91
    }
92
93
    /**
94
     * Configure the variables for Pagantis payment method.
95
     *
96
     * @return bool
97
     */
98
    public function install()
99
    {
100
        if (!extension_loaded('curl')) {
101
            $this->installErrors[] =
102
                $this->l('You have to enable the cURL extension on your server to install this module');
103
            return false;
104
        }
105
        if (!version_compare(phpversion(), '5.3.0', '>=')) {
106
            $this->installErrors[] = $this->l('The PHP version bellow 5.3.0 is not supported');
107
            return false;
108
        }
109
        $curl_info = curl_version();
110
        $curl_version = $curl_info['version'];
111
        if (!version_compare($curl_version, '7.34.0', '>=')) {
112
            $this->installErrors[] = $this->l('Curl Version is lower than 7.34.0 and does not support TLS 1.2');
113
            return false;
114
        }
115
116
        Configuration::updateValue('pagantis_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...
117
        Configuration::updateValue('pagantis_simulator_is_enabled', 1);
118
        Configuration::updateValue('pagantis_public_key', '');
119
        Configuration::updateValue('pagantis_private_key', '');
120
121
        return (parent::install()
122
            && $this->registerHook('displayShoppingCart')
123
            && $this->registerHook('payment')
124
            && $this->registerHook('paymentOptions')
125
            && $this->registerHook('displayRightColumn')
126
            && $this->registerHook('displayLeftColumn')
127
            && $this->registerHook('displayRightColumnProduct')
128
            && $this->registerHook('displayLeftColumnProduct')
129
            && $this->registerHook('displayProductButtons')
130
            && $this->registerHook('displayOrderConfirmation')
131
            && $this->registerHook('header')
132
        );
133
    }
134
135
    /**
136
     * Remove the production private api key and remove the files
137
     *
138
     * @return bool
139
     */
140
    public function uninstall()
141
    {
142
        Configuration::deleteByName('PAYLATER_PRIVATE_KEY_PROD');
143
144
        return parent::uninstall();
145
    }
146
147
    /**
148
     * Migrate the configs of older versions < 7x to new configurations
149
     */
150
    public function migrate()
151
    {
152
        if (Configuration::get('PAYLATER_MIN_AMOUNT')) {
153
            Db::getInstance()->update(
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...
154
                'pagantis_config',
155
                array('value' => Configuration::get('PAYLATER_MIN_AMOUNT')),
156
                'config = \'PAGANTIS_DISPLAY_MIN_AMOUNT\''
157
            );
158
            Configuration::updateValue('PAYLATER_MIN_AMOUNT', false);
159
            Configuration::updateValue('pagantis_is_enabled', 1);
160
            Configuration::updateValue('pagantis_simulator_is_enabled', 1);
161
162
            // migrating pk/tk from previous version
163
            if (Configuration::get('pagantis_public_key') === false
164
                && Configuration::get('PAYLATER_PUBLIC_KEY_PROD')
165
            ) {
166
                Configuration::updateValue('pagantis_public_key', Configuration::get('PAYLATER_PUBLIC_KEY_PROD'));
167
                Configuration::updateValue('PAYLATER_PUBLIC_KEY_PROD', false);
168
            } elseif (Configuration::get('pagantis_public_key') === false
169
                && Configuration::get('PAYLATER_PUBLIC_KEY_TEST')
170
            ) {
171
                Configuration::updateValue('pagantis_public_key', Configuration::get('PAYLATER_PUBLIC_KEY_TEST'));
172
                Configuration::updateValue('PAYLATER_PUBLIC_KEY_TEST', false);
173
            }
174
175
            if (Configuration::get('pagantis_private_key') === false
176
                && Configuration::get('PAYLATER_PRIVATE_KEY_PROD')
177
            ) {
178
                Configuration::updateValue('pagantis_private_key', Configuration::get('PAYLATER_PRIVATE_KEY_PROD'));
179
                Configuration::updateValue('PAYLATER_PRIVATE_KEY_PROD', false);
180
            } elseif (Configuration::get('pagantis_private_key') === false
181
                && Configuration::get('PAYLATER_PRIVATE_KEY_TEST')
182
            ) {
183
                Configuration::updateValue('pagantis_private_key', Configuration::get('PAYLATER_PRIVATE_KEY_TEST'));
184
                Configuration::updateValue('PAYLATER_PRIVATE_KEY_TEST', false);
185
            }
186
        }
187
    }
188
189
    /**
190
     * Check if new hooks used in new 7x versions are enabled and activate them if needed
191
     *
192
     * @throws PrestaShopDatabaseException
193
     */
194
    public function checkHooks()
195
    {
196
        try {
197
            $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...
198
            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...
199
            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...
200
            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...
201
            $hook_exists = Db::getInstance()->ExecuteS($sql_content);
202
            if (empty($hook_exists)) {
203
                $sql_insert = 'insert into ' . _DB_PREFIX_.  'hook_module 
204
            (id_module, id_shop, id_hook, position)
205
            values
206
            (\''. Module::getModuleIdByName($this->name) . '\',
207
            \''. Shop::getContextShopID() . '\',
208
            \''. Hook::getIdByName('header') . '\',
209
            150)';
210
                Db::getInstance()->execute($sql_insert);
211
            }
212
        } catch (\Exception $exception) {
213
            // continue without errors
214
        }
215
    }
216
217
    public function loadEnvVariables()
218
    {
219
        $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...
220
        $dbConfigs = Db::getInstance()->executeS($sql_content);
221
222
        // Convert a multimple dimension array for SQL insert statements into a simple key/value
223
        $simpleDbConfigs = array();
224
        foreach ($dbConfigs as $config) {
225
            $simpleDbConfigs[$config['config']] = $config['value'];
226
        }
227
        $newConfigs = array_diff_key($this->defaultConfigs, $simpleDbConfigs);
228
        if (!empty($newConfigs)) {
229
            $data = array();
230
            foreach ($newConfigs as $key => $value) {
231
                $data[] = array(
232
                    'config' => $key,
233
                    'value' => $value,
234
                );
235
            }
236
            Db::getInstance()->insert('pagantis_config', $data);
237
        }
238
239
        foreach (array_merge($this->defaultConfigs, $simpleDbConfigs) as $key => $value) {
240
            putenv($key . '=' . $value);
241
        }
242
243
        putenv("PAGANTIS_DEFAULT_CONFIGS" . '=' . json_encode($this->defaultConfigs));
244
    }
245
246
    /**
247
     * @param $sql_file
248
     * @return bool
249
     */
250
    public function loadSQLFile($sql_file)
251
    {
252
        $sql_content = Tools::file_get_contents($sql_file);
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...
253
        $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...
254
        $sql_requests = preg_split("/;\s*[\r\n]+/", $sql_content);
255
256
        $result = true;
257
        foreach ($sql_requests as $request) {
258
            if (!empty($request)) {
259
                $result &= Db::getInstance()->execute(trim($request));
260
            }
261
        }
262
263
        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...
264
    }
265
266
    /**
267
     * Check amount of order > minAmount
268
     * Check valid currency
269
     * Check API variables are set
270
     *
271
     * @return bool
272
     * @throws PrestaShopDatabaseException
273
     * @throws PrestaShopException
274
     */
275
    public function isPaymentMethodAvailable()
276
    {
277
        $cart                       = $this->context->cart;
278
        $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...
279
        $availableCurrencies        = array('EUR');
280
        $pagantisDisplayMinAmount        = getenv('PAGANTIS_DISPLAY_MIN_AMOUNT');
281
        $pagantisPublicKey               = Configuration::get('pagantis_public_key');
282
        $pagantisPrivateKey              = Configuration::get('pagantis_private_key');
283
284
        return (
285
            $cart->getOrderTotal() >= $pagantisDisplayMinAmount &&
286
            in_array($currency->iso_code, $availableCurrencies) &&
287
            $pagantisPublicKey &&
288
            $pagantisPrivateKey
289
        );
290
    }
291
292
    /**
293
     * @param Cart $cart
294
     *
295
     * @return array
296
     * @throws Exception
297
     */
298
    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...
299
    {
300
        $currency = new Currency(($cart->id_currency));
301
302
        return array(
303
            'pagantis_button' => '#pagantis_payment_button',
304
            'pagantis_currency_iso' => $currency->iso_code,
305
            'pagantis_cart_total' => $cart->getOrderTotal(),
306
        );
307
    }
308
309
    /**
310
     * Header hook
311
     */
312
    public function hookHeader()
313
    {
314
        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...
315
            $this->context->controller->registerJavascript(
316
                sha1(mt_rand(1, 90000)),
317
                'https://cdn.pagamastarde.com/js/pmt-v2/sdk.js',
318
                array('server' => 'remote')
319
            );
320
        } else {
321
            $this->context->controller->addJS('https://cdn.pagamastarde.com/js/pmt-v2/sdk.js');
322
        }
323
        $this->context->controller->addJS($this->getPathUri(). 'views/js/simulator.js');
324
    }
325
326
    /**
327
     * @return array
328
     * @throws Exception
329
     */
330
    public function hookPaymentOptions()
331
    {
332
        die("dsfdsf");
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
333
        if (!$this->isPaymentMethodAvailable()) {
0 ignored issues
show
Unused Code introduced by
IfNode is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
334
            return array();
335
        }
336
337
        /** @var Cart $cart */
338
        $cart                            = $this->context->cart;
339
        $orderTotal                      = $cart->getOrderTotal();
340
        $link                            = $this->context->link;
341
        $pagantisPublicKey               = Configuration::get('pagantis_public_key');
342
        $pagantisSimulatorIsEnabled      = Configuration::get('pagantis_simulator_is_enabled');
343
        $pagantisIsEnabled               = Configuration::get('pagantis_is_enabled');
344
        $pagantisSimulatorType           = getenv('PAGANTIS_SIMULATOR_DISPLAY_TYPE');
345
        $pagantisSimulatorCSSSelector    = getenv('PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR');
346
        $pagantisSimulatorPriceSelector  = getenv('PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR');
347
        $pagantisSimulatorQuotesStart    = getenv('PAGANTIS_SIMULATOR_START_INSTALLMENTS');
348
        $pagantisSimulatorSkin           = getenv('PAGANTIS_SIMULATOR_DISPLAY_SKIN');
349
        $pagantisSimulatorPosition       = getenv('PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION');
350
        $pagantisTitle                   = $this->l(getenv('PAGANTIS_TITLE'));
351
352
        $this->context->smarty->assign($this->getButtonTemplateVars($cart));
353
        $this->context->smarty->assign(array(
354
            'amount'                     => $orderTotal,
355
            'pagantisPublicKey'          => $pagantisPublicKey,
356
            'pagantisCSSSelector'        => $pagantisSimulatorCSSSelector,
357
            'pagantisPriceSelector'      => $pagantisSimulatorPriceSelector,
358
            'pagantisQuotesStart'        => $pagantisSimulatorQuotesStart,
359
            'pagantisSimulatorIsEnabled' => $pagantisSimulatorIsEnabled,
360
            'pagantisSimulatorType'      => $pagantisSimulatorType,
361
            'pagantisSimulatorSkin'      => $pagantisSimulatorSkin,
362
            'pagantisSimulatorPosition'  => $pagantisSimulatorPosition,
363
            'pagantisIsEnabled'          => $pagantisIsEnabled,
364
            'pagantisTitle'              => $pagantisTitle,
365
            'paymentUrl'                 => $link->getModuleLink('pagantis', 'payment'),
366
            '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...
367
        ));
368
369
        $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...
370
        $paymentOption
371
            ->setCallToActionText($pagantisTitle)
372
            ->setAction($link->getModuleLink('pagantis', 'payment'))
373
            ->setLogo($this->getPathUri(). 'logo.gif')
374
            ->setModuleName(__CLASS__)
375
        ;
376
377
378
        if (_PS_VERSION_ < 1.7) {
379
            $paymentOption->setAdditionalInformation(
380
                $this->fetch('module:pagantis/views/templates/hook/checkout-15.tpl')
381
            );
382
        }
383
384
        return array($paymentOption);
385
    }
386
387
    /**
388
     * Get the form for editing the BackOffice options of the module
389
     *
390
     * @return array
391
     */
392
    private function getConfigForm()
393
    {
394
        return array(
395
            'form' => array(
396
                'legend' => array(
397
                    'title' => $this->l('Basic Settings'),
398
                    'icon' => 'icon-cogs',
399
                ),
400
                'input' => array(
401
                    array(
402
                        'name' => 'pagantis_is_enabled',
403
                        '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...
404
                        'label' => $this->l('Module is enabled'),
405
                        'prefix' => '<i class="icon icon-key"></i>',
406
                        'class' => 't',
407
                        'required' => true,
408
                        'values'=> array(
409
                            array(
410
                                'id' => 'pagantis_is_enabled_true',
411
                                'value' => 1,
412
                                'label' => $this->l('Yes', get_class($this), null, false),
413
                            ),
414
                            array(
415
                                'id' => 'pagantis_is_enabled_false',
416
                                'value' => 0,
417
                                'label' => $this->l('No', get_class($this), null, false),
418
                            ),
419
                        )
420
                    ),
421
                    array(
422
                        'name' => 'pagantis_public_key',
423
                        'suffix' => $this->l('ex: pk_fd53cd467ba49022e4gf215e'),
424
                        'type' => 'text',
425
                        'size' => 60,
426
                        'label' => $this->l('Public Key'),
427
                        'prefix' => '<i class="icon icon-key"></i>',
428
                        'col' => 6,
429
                        'required' => true,
430
                    ),
431
                    array(
432
                        'name' => 'pagantis_private_key',
433
                        'suffix' => $this->l('ex: 21e5723a97459f6a'),
434
                        'type' => 'text',
435
                        'size' => 60,
436
                        'label' => $this->l('Secret Key'),
437
                        'prefix' => '<i class="icon icon-key"></i>',
438
                        'col' => 6,
439
                        'required' => true,
440
                    ),
441
                    array(
442
                        'name' => 'pagantis_simulator_is_enabled',
443
                        'type' => (version_compare(_PS_VERSION_, '1.6')<0) ?'radio' :'switch',
444
                        'label' => $this->l('Simulator is enabled'),
445
                        'prefix' => '<i class="icon icon-key"></i>',
446
                        'class' => 't',
447
                        'required' => true,
448
                        'values'=> array(
449
                            array(
450
                                'id' => 'pagantis_simulator_is_enabled_on',
451
                                'value' => 1,
452
                                'label' => $this->l('Yes'),
453
                            ),
454
                            array(
455
                                'id' => 'pagantis_simulator_is_enabled_off',
456
                                'value' => 0,
457
                                'label' => $this->l('No'),
458
                            ),
459
                        )
460
                    ),
461
                ),
462
                'submit' => array(
463
                    'title' => $this->l('Save'),
464
                ),
465
            ),
466
        );
467
    }
468
469
    /**
470
     * Form configuration function
471
     *
472
     * @param array $settings
473
     *
474
     * @return string
475
     */
476
    private function renderForm(array $settings)
477
    {
478
        $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...
479
        $helper->show_toolbar = false;
480
        $helper->table = $this->table;
481
        $helper->module = $this;
482
        $helper->default_form_language = $this->context->language->id;
483
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
484
        $helper->identifier = $this->identifier;
485
        $helper->submit_action = 'submit'.$this->name;
486
        $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...
487
        $helper->token = Tools::getAdminTokenLite('AdminModules');
488
        $helper->tpl_vars = array(
489
            'fields_value' => $settings,
490
            'languages' => $this->context->controller->getLanguages(),
491
            'id_language' => $this->context->language->id,
492
        );
493
494
        $helper->fields_value['pagantis_url_ok'] = Configuration::get('pagantis_url_ok');
495
496
        return $helper->generateForm(array($this->getConfigForm()));
497
    }
498
499
    /**
500
     * Function to update the variables of Pagantis Module in the backoffice of prestashop
501
     *
502
     * @return string
503
     * @throws SmartyException
504
     */
505
    public function getContent()
506
    {
507
        $error = '';
508
        $message = '';
509
        $settings = array();
510
        $settings['pagantis_public_key'] = Configuration::get('pagantis_public_key');
511
        $settings['pagantis_private_key'] = Configuration::get('pagantis_private_key');
512
        $settingsKeys = array(
513
            'pagantis_is_enabled',
514
            'pagantis_public_key',
515
            'pagantis_private_key',
516
            'pagantis_simulator_is_enabled',
517
        );
518
519
        //Different Behavior depending on 1.6 or earlier
520
        if (Tools::isSubmit('submit'.$this->name)) {
521
            foreach ($settingsKeys as $key) {
522
                switch ($key) {
523
                    case 'pagantis_public_key':
524
                        $value = Tools::getValue($key);
525
                        if (!$value) {
526
                            $error = $this->l('Please add a Pagantis API Public Key');
527
                            break;
528
                        }
529
                        Configuration::updateValue($key, $value);
530
                        $settings[$key] = $value;
531
                        break;
532
                    case 'pagantis_private_key':
533
                        $value = Tools::getValue($key);
534
                        if (!$value) {
535
                            $error = $this->l('Please add a Pagantis API Private Key');
536
                            break;
537
                        }
538
                        Configuration::updateValue($key, $value);
539
                        $settings[$key] = $value;
540
                        break;
541
                    default:
542
                        $value = Tools::getValue($key);
543
                        Configuration::updateValue($key, $value);
544
                        $settings[$key] = $value;
545
                        break;
546
                }
547
                $message = $this->displayConfirmation($this->l('All changes have been saved'));
548
            }
549
        } else {
550
            foreach ($settingsKeys as $key) {
551
                    $settings[$key] = Configuration::get($key);
552
            }
553
        }
554
555
        if ($error) {
556
            $message = $this->displayError($error);
557
        }
558
559
        $logo = $this->getPathUri(). 'views/img/logo_pagantis.png';
560
        $tpl = $this->local_path.'views/templates/admin/config-info.tpl';
561
        $this->context->smarty->assign(array(
562
            'logo' => $logo,
563
            'form' => $this->renderForm($settings),
564
            'message' => $message,
565
            'version' => 'v'.$this->version,
566
        ));
567
568
        return $this->context->smarty->fetch($tpl);
569
    }
570
571
    /**
572
     * Hook to show payment method, this only applies on prestashop <= 1.6
573
     *
574
     * @param $params
575
     * @return bool | string
576
     * @throws Exception
577
     */
578
    public function hookPayment($params)
579
    {
580
        if (!$this->isPaymentMethodAvailable()) {
581
            return false;
582
        }
583
584
        /** @var Cart $cart */
585
        $cart                            = $params['cart'];
586
        $orderTotal                      = $cart->getOrderTotal();
587
        $link                            = $this->context->link;
588
        $pagantisPublicKey               = Configuration::get('pagantis_public_key');
589
        $pagantisSimulatorIsEnabled      = Configuration::get('pagantis_simulator_is_enabled');
590
        $pagantisIsEnabled               = Configuration::get('pagantis_is_enabled');
591
        $pagantisSimulatorType           = getenv('PAGANTIS_SIMULATOR_DISPLAY_TYPE');
592
        $pagantisSimulatorCSSSelector    = getenv('PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR');
593
        $pagantisSimulatorPriceSelector  = getenv('PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR');
594
        $pagantisSimulatorQuotesStart    = getenv('PAGANTIS_SIMULATOR_START_INSTALLMENTS');
595
        $pagantisSimulatorSkin           = getenv('PAGANTIS_SIMULATOR_DISPLAY_SKIN');
596
        $pagantisSimulatorPosition       = getenv('PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION');
597
        $pagantisTitle                   = $this->l(getenv('PAGANTIS_TITLE'));
598
        $this->context->smarty->assign($this->getButtonTemplateVars($cart));
599
        $this->context->smarty->assign(array(
600
            'amount'                     => $orderTotal,
601
            'pagantisPublicKey'          => $pagantisPublicKey,
602
            'pagantisCSSSelector'        => $pagantisSimulatorCSSSelector,
603
            'pagantisPriceSelector'      => $pagantisSimulatorPriceSelector,
604
            'pagantisQuotesStart'        => $pagantisSimulatorQuotesStart,
605
            'pagantisSimulatorIsEnabled' => $pagantisSimulatorIsEnabled,
606
            'pagantisSimulatorType'      => $pagantisSimulatorType,
607
            'pagantisSimulatorSkin'      => $pagantisSimulatorSkin,
608
            'pagantisSimulatorPosition'  => $pagantisSimulatorPosition,
609
            'pagantisIsEnabled'          => $pagantisIsEnabled,
610
            'pagantisTitle'              => $pagantisTitle,
611
            'paymentUrl'                 => $link->getModuleLink('pagantis', 'payment'),
612
            '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...
613
        ));
614
615
        $supercheckout_enabled = Module::isEnabled('supercheckout');
616
        $onepagecheckoutps_enabled = Module::isEnabled('onepagecheckoutps');
617
        $onepagecheckout_enabled = Module::isEnabled('onepagecheckout');
618
619
        $return = true;
620
        if ($supercheckout_enabled || $onepagecheckout_enabled || $onepagecheckoutps_enabled) {
621
            $this->checkLogoExists();
622
            $return = $this->display(__FILE__, 'views/templates/hook/onepagecheckout.tpl');
623
        } elseif (_PS_VERSION_ < 1.7) {
624
            $return = $this->display(__FILE__, 'views/templates/hook/checkout-15.tpl');
625
        }
626
        return $return;
627
    }
628
629
    /**
630
     * @param string $functionName
631
     *:
632
     * @return string
633
     * @throws PrestaShopDatabaseException
634
     * @throws PrestaShopException
635
     */
636
    public function productPageSimulatorDisplay($functionName)
637
    {
638
        $productConfiguration = getenv('PAGANTIS_SIMULATOR_DISPLAY_POSITION');
639
        /** @var ProductCore $product */
640
        $product = new Product(Tools::getValue('id_product'));
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...
641
        $amount = $product->getPublicPrice();
642
        $pagantisPublicKey                 = Configuration::get('pagantis_public_key');
643
        $pagantisSimulatorIsEnabled        = Configuration::get('pagantis_simulator_is_enabled');
644
        $pagantisIsEnabled                 = Configuration::get('pagantis_is_enabled');
645
        $pagantisSimulatorType             = getenv('PAGANTIS_SIMULATOR_DISPLAY_TYPE');
646
        $pagantisSimulatorCSSSelector      = getenv('PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR');
647
        $pagantisSimulatorPriceSelector    = getenv('PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR');
648
        $pagantisSimulatorQuantitySelector = getenv('PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR');
649
        $pagantisSimulatorQuotesStart      = getenv('PAGANTIS_SIMULATOR_START_INSTALLMENTS');
650
        $pagantisSimulatorSkin             = getenv('PAGANTIS_SIMULATOR_DISPLAY_SKIN');
651
        $pagantisSimulatorPosition         = getenv('PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION');
652
        $pagantisDisplayMinAmount          = getenv('PAGANTIS_DISPLAY_MIN_AMOUNT');
653
654
        if ($functionName != $productConfiguration ||
655
            $amount <= 0 ||
656
            $amount < $pagantisDisplayMinAmount ||
657
            !$pagantisSimulatorType
658
        ) {
659
            return null;
660
        }
661
662
        $this->context->smarty->assign(array(
663
            'amount'                     => $amount,
664
            'pagantisPublicKey'          => $pagantisPublicKey,
665
            'pagantisCSSSelector'        => $pagantisSimulatorCSSSelector,
666
            'pagantisPriceSelector'      => $pagantisSimulatorPriceSelector,
667
            'pagantisQuantitySelector'   => $pagantisSimulatorQuantitySelector,
668
            'pagantisSimulatorIsEnabled' => $pagantisSimulatorIsEnabled,
669
            'pagantisIsEnabled'          => $pagantisIsEnabled,
670
            'pagantisSimulatorType'      => $pagantisSimulatorType,
671
            'pagantisSimulatorSkin'      => $pagantisSimulatorSkin,
672
            'pagantisSimulatorPosition'  => $pagantisSimulatorPosition,
673
            'pagantisQuotesStart'        => $pagantisSimulatorQuotesStart,
674
        ));
675
676
        return $this->display(__FILE__, 'views/templates/hook/product-simulator.tpl');
677
    }
678
679
    /**
680
     * @return string
681
     * @throws PrestaShopDatabaseException
682
     * @throws PrestaShopException
683
     */
684
    public function hookDisplayRightColumn()
685
    {
686
687
        return $this->productPageSimulatorDisplay(__FUNCTION__);
688
    }
689
690
    /**
691
     * @return string
692
     * @throws PrestaShopDatabaseException
693
     * @throws PrestaShopException
694
     */
695
    public function hookDisplayLeftColumn()
696
    {
697
        return $this->productPageSimulatorDisplay(__FUNCTION__);
698
    }
699
700
    /**
701
     * @return string
702
     * @throws PrestaShopDatabaseException
703
     * @throws PrestaShopException
704
     */
705
    public function hookDisplayRightColumnProduct()
706
    {
707
        return $this->productPageSimulatorDisplay(__FUNCTION__);
708
    }
709
710
    /**
711
     * @return string
712
     * @throws PrestaShopDatabaseException
713
     * @throws PrestaShopException
714
     */
715
    public function hookDisplayLeftColumnProduct()
716
    {
717
        return $this->productPageSimulatorDisplay(__FUNCTION__);
718
    }
719
720
    /**
721
     * @return string
722
     * @throws PrestaShopDatabaseException
723
     * @throws PrestaShopException
724
     */
725
    public function hookDisplayProductButtons()
726
    {
727
        return $this->productPageSimulatorDisplay(__FUNCTION__);
728
    }
729
730
    /**
731
     * @param array $params
732
     *
733
     * @return string
734
     */
735
    public function hookDisplayOrderConfirmation($params)
736
    {
737
        $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...
738
739
        if ($paymentMethod == $this->displayName) {
740
            return $this->display(__FILE__, 'views/templates/hook/payment-return.tpl');
741
        }
742
743
        return null;
744
    }
745
746
    /**
747
     * Check logo exists in OPC module
748
     */
749
    public function checkLogoExists()
750
    {
751
        $logo = _PS_MODULE_DIR_ . '/onepagecheckoutps/views/img/payments/'. Tools::strtolower(__CLASS__). '.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...
752
        if (!file_exists($logo) && is_dir(_PS_MODULE_DIR_ . '/onepagecheckoutps/views/img/payments')) {
753
            copy(
754
                _PS_PAYLATER_DIR . '/views/img/logo-64x64.png',
755
                $logo
756
            );
757
        }
758
    }
759
}
760