Completed
Push — master ( 30e125...baa9ff )
by Cesar
19s queued 11s
created

Paylater::checkEnvVariables()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 13
nc 6
nop 0
dl 0
loc 20
rs 9.8333
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of the official Paylater module for PrestaShop.
4
 *
5
 * @author    Paga+Tarde <[email protected]>
6
 * @copyright 2015-2016 Paga+Tarde
7
 * @license   proprietary
8
 */
9
10
if (!defined('_PS_VERSION_')) {
11
    exit;
12
}
13
14
define('_PS_PAYLATER_DIR', _PS_MODULE_DIR_. '/paylater');
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 Paylater
20
 */
21
class Paylater 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://pagamastarde.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
        'PMT_TITLE' => 'Instant Financing',
45
        'PMT_SIMULATOR_DISPLAY_TYPE' => 'pmtSDK.simulator.types.SIMPLE',
46
        'PMT_SIMULATOR_DISPLAY_SKIN' => 'pmtSDK.simulator.skins.BLUE',
47
        'PMT_SIMULATOR_DISPLAY_POSITION' => 'hookDisplayProductButtons',
48
        'PMT_SIMULATOR_START_INSTALLMENTS' => '3',
49
        'PMT_SIMULATOR_CSS_POSITION_SELECTOR' => 'default',
50
        'PMT_SIMULATOR_DISPLAY_CSS_POSITION' => 'pmtSDK.simulator.positions.INNER',
51
        'PMT_SIMULATOR_CSS_PRICE_SELECTOR' => 'default',
52
        'PMT_SIMULATOR_CSS_QUANTITY_SELECTOR' => 'default',
53
        'PMT_FORM_DISPLAY_TYPE' => '0',
54
        'PMT_DISPLAY_MIN_AMOUNT' => '1',
55
        'PMT_URL_OK' => '',
56
        'PMT_URL_KO' => '',
57
    );
58
59
    /**
60
     * Paylater 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 = 'paylater';
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 = '7.2.2';
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 = 'Paga+Tarde';
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('Paga+Tarde');
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->checkEnvVariables();
85
86
        $this->migrate();
87
88
        $this->checkHooks();
89
90
        parent::__construct();
91
    }
92
93
    /**
94
     * Configure the variables for paga+tarde 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('pmt_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('pmt_simulator_is_enabled', 1);
118
        Configuration::updateValue('pmt_public_key', '');
119
        Configuration::updateValue('pmt_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
                'pmt_config',
155
                array('value' => Configuration::get('PAYLATER_MIN_AMOUNT')),
156
                'config = \'PMT_DISPLAY_MIN_AMOUNT\''
157
            );
158
            Configuration::updateValue('PAYLATER_MIN_AMOUNT', false);
159
            Configuration::updateValue('pmt_is_enabled', 1);
160
            Configuration::updateValue('pmt_simulator_is_enabled', 1);
161
162
            // migrating pk/tk from previous version
163
            if (Configuration::get('pmt_public_key') === false
164
                && Configuration::get('PAYLATER_PUBLIC_KEY_PROD')
165
            ) {
166
                Configuration::updateValue('pmt_public_key', Configuration::get('PAYLATER_PUBLIC_KEY_PROD'));
167
                Configuration::updateValue('PAYLATER_PUBLIC_KEY_PROD', false);
168
            } elseif (Configuration::get('pmt_public_key') === false
169
                && Configuration::get('PAYLATER_PUBLIC_KEY_TEST')
170
            ) {
171
                Configuration::updateValue('pmt_public_key', Configuration::get('PAYLATER_PUBLIC_KEY_TEST'));
172
                Configuration::updateValue('PAYLATER_PUBLIC_KEY_TEST', false);
173
            }
174
175
            if (Configuration::get('pmt_private_key') === false
176
                && Configuration::get('PAYLATER_PRIVATE_KEY_PROD')
177
            ) {
178
                Configuration::updateValue('pmt_private_key', Configuration::get('PAYLATER_PRIVATE_KEY_PROD'));
179
                Configuration::updateValue('PAYLATER_PRIVATE_KEY_PROD', false);
180
            } elseif (Configuration::get('pmt_private_key') === false
181
                && Configuration::get('PAYLATER_PRIVATE_KEY_TEST')
182
            ) {
183
                Configuration::updateValue('pmt_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
    /**
218
     * @throws PrestaShopDatabaseException
219
     */
220
    public function checkEnvVariables()
221
    {
222
        $sql_content = 'select * from ' . _DB_PREFIX_. 'pmt_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...
223
        $dbConfigs = Db::getInstance()->executeS($sql_content);
224
225
        // Convert a multimple dimension array for SQL insert statements into a simple key/value
226
        $simpleDbConfigs = array();
227
        foreach ($dbConfigs as $config) {
228
            $simpleDbConfigs[$config['config']] = $config['value'];
229
        }
230
        $newConfigs = array_diff_key($this->defaultConfigs, $simpleDbConfigs);
231
        if (!empty($newConfigs)) {
232
            $data = array();
233
            foreach ($newConfigs as $key => $value) {
234
                $data[] = array(
235
                    'config' => $key,
236
                    'value' => $value,
237
                );
238
            }
239
            Db::getInstance()->insert('pmt_config', $data);
240
        }
241
    }
242
243
    /**
244
     * @param $sql_file
245
     * @return bool
246
     */
247
    public function loadSQLFile($sql_file)
248
    {
249
        $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...
250
        $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...
251
        $sql_requests = preg_split("/;\s*[\r\n]+/", $sql_content);
252
253
        $result = true;
254
        foreach ($sql_requests as $request) {
255
            if (!empty($request)) {
256
                $result &= Db::getInstance()->execute(trim($request));
257
            }
258
        }
259
260
        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...
261
    }
262
263
    /**
264
     * Check amount of order > minAmount
265
     * Check valid currency
266
     * Check API variables are set
267
     *
268
     * @return bool
269
     * @throws PrestaShopDatabaseException
270
     * @throws PrestaShopException
271
     */
272
    public function isPaymentMethodAvailable()
273
    {
274
        $cart                       = $this->context->cart;
275
        $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...
276
        $availableCurrencies        = array('EUR');
277
        $pmtDisplayMinAmount        = Paylater::getExtraConfig('PMT_DISPLAY_MIN_AMOUNT');
278
        $pmtPublicKey               = Configuration::get('pmt_public_key');
279
        $pmtPrivateKey              = Configuration::get('pmt_private_key');
280
281
        return (
282
            $cart->getOrderTotal() >= $pmtDisplayMinAmount &&
283
            in_array($currency->iso_code, $availableCurrencies) &&
284
            $pmtPublicKey &&
285
            $pmtPrivateKey
286
        );
287
    }
288
289
    /**
290
     * @param Cart $cart
291
     *
292
     * @return array
293
     * @throws Exception
294
     */
295
    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...
296
    {
297
        $currency = new Currency(($cart->id_currency));
298
299
        return array(
300
            'paylater_button' => '#paylater_payment_button',
301
            'paylater_currency_iso' => $currency->iso_code,
302
            'paylater_cart_total' => $cart->getOrderTotal(),
303
        );
304
    }
305
306
    /**
307
     * Header hook
308
     */
309
    public function hookHeader()
310
    {
311
        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...
312
            $this->context->controller->registerJavascript(
313
                sha1(mt_rand(1, 90000)),
314
                'https://cdn.pagamastarde.com/js/pmt-v2/sdk.js',
315
                array('server' => 'remote')
316
            );
317
        } else {
318
            $this->context->controller->addJS('https://cdn.pagamastarde.com/js/pmt-v2/sdk.js');
319
        }
320
        $this->context->controller->addJS($this->getPathUri(). 'views/js/simulator.js');
321
    }
322
323
    /**
324
     * @return array
325
     * @throws Exception
326
     */
327
    public function hookPaymentOptions()
328
    {
329
        if (!$this->isPaymentMethodAvailable()) {
330
            return array();
331
        }
332
333
        /** @var Cart $cart */
334
        $cart                       = $this->context->cart;
335
        $orderTotal                 = $cart->getOrderTotal();
336
        $link                       = $this->context->link;
337
        $pmtPublicKey               = Configuration::get('pmt_public_key');
338
        $pmtSimulatorIsEnabled      = Configuration::get('pmt_simulator_is_enabled');
339
        $pmtIsEnabled               = Configuration::get('pmt_is_enabled');
340
        $pmtSimulatorType           = Paylater::getExtraConfig('PMT_SIMULATOR_DISPLAY_TYPE');
341
        $pmtSimulatorCSSSelector    = Paylater::getExtraConfig('PMT_SIMULATOR_CSS_POSITION_SELECTOR');
342
        $pmtSimulatorPriceSelector  = Paylater::getExtraConfig('PMT_SIMULATOR_CSS_PRICE_SELECTOR');
343
        $pmtSimulatorQuotesStart    = Paylater::getExtraConfig('PMT_SIMULATOR_START_INSTALLMENTS');
344
        $pmtSimulatorSkin           = Paylater::getExtraConfig('PMT_SIMULATOR_DISPLAY_SKIN');
345
        $pmtSimulatorPosition       = Paylater::getExtraConfig('PMT_SIMULATOR_DISPLAY_CSS_POSITION');
346
        $pmtTitle                   = $this->l(Paylater::getExtraConfig('PMT_TITLE'));
347
348
        $this->context->smarty->assign($this->getButtonTemplateVars($cart));
349
        $this->context->smarty->assign(array(
350
            'amount'                => $orderTotal,
351
            'pmtPublicKey'          => $pmtPublicKey,
352
            'pmtCSSSelector'        => $pmtSimulatorCSSSelector,
353
            'pmtPriceSelector'      => $pmtSimulatorPriceSelector,
354
            'pmtQuotesStart'        => $pmtSimulatorQuotesStart,
355
            'pmtSimulatorIsEnabled' => $pmtSimulatorIsEnabled,
356
            'pmtSimulatorType'      => $pmtSimulatorType,
357
            'pmtSimulatorSkin'      => $pmtSimulatorSkin,
358
            'pmtSimulatorPosition'  => $pmtSimulatorPosition,
359
            'pmtIsEnabled'          => $pmtIsEnabled,
360
            'pmtTitle'              => $pmtTitle,
361
            'paymentUrl'            => $link->getModuleLink('paylater', 'payment'),
362
            '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...
363
        ));
364
365
        $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...
366
        $paymentOption
367
            ->setCallToActionText($pmtTitle)
368
            ->setAction($link->getModuleLink('paylater', 'payment'))
369
            ->setLogo($this->getPathUri(). 'logo.gif')
370
            ->setModuleName(__CLASS__)
371
        ;
372
373
374
        if (_PS_VERSION_ < 1.7) {
375
            $paymentOption->setAdditionalInformation(
376
                $this->fetch('module:paylater/views/templates/hook/checkout-15.tpl')
377
            );
378
        }
379
380
        return array($paymentOption);
381
    }
382
383
    /**
384
     * Get the form for editing the BackOffice options of the module
385
     *
386
     * @return array
387
     */
388
    private function getConfigForm()
389
    {
390
        return array(
391
            'form' => array(
392
                'legend' => array(
393
                    'title' => $this->l('Basic Settings'),
394
                    'icon' => 'icon-cogs',
395
                ),
396
                'input' => array(
397
                    array(
398
                        'name' => 'pmt_is_enabled',
399
                        '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...
400
                        'label' => $this->l('Module is enabled'),
401
                        'prefix' => '<i class="icon icon-key"></i>',
402
                        'class' => 't',
403
                        'required' => true,
404
                        'values'=> array(
405
                            array(
406
                                'id' => 'pmt_is_enabled_true',
407
                                'value' => 1,
408
                                'label' => $this->l('Yes', get_class($this), null, false),
409
                            ),
410
                            array(
411
                                'id' => 'pmt_is_enabled_false',
412
                                'value' => 0,
413
                                'label' => $this->l('No', get_class($this), null, false),
414
                            ),
415
                        )
416
                    ),
417
                    array(
418
                        'name' => 'pmt_public_key',
419
                        'suffix' => $this->l('ex: pk_fd53cd467ba49022e4gf215e'),
420
                        'type' => 'text',
421
                        'size' => 60,
422
                        'label' => $this->l('Public Key'),
423
                        'prefix' => '<i class="icon icon-key"></i>',
424
                        'col' => 6,
425
                        'required' => true,
426
                    ),
427
                    array(
428
                        'name' => 'pmt_private_key',
429
                        'suffix' => $this->l('ex: 21e5723a97459f6a'),
430
                        'type' => 'text',
431
                        'size' => 60,
432
                        'label' => $this->l('Secret Key'),
433
                        'prefix' => '<i class="icon icon-key"></i>',
434
                        'col' => 6,
435
                        'required' => true,
436
                    ),
437
                    array(
438
                        'name' => 'pmt_simulator_is_enabled',
439
                        'type' => (version_compare(_PS_VERSION_, '1.6')<0) ?'radio' :'switch',
440
                        'label' => $this->l('Simulator is enabled'),
441
                        'prefix' => '<i class="icon icon-key"></i>',
442
                        'class' => 't',
443
                        'required' => true,
444
                        'values'=> array(
445
                            array(
446
                                'id' => 'pmt_simulator_is_enabled_on',
447
                                'value' => 1,
448
                                'label' => $this->l('Yes'),
449
                            ),
450
                            array(
451
                                'id' => 'pmt_simulator_is_enabled_off',
452
                                'value' => 0,
453
                                'label' => $this->l('No'),
454
                            ),
455
                        )
456
                    ),
457
                ),
458
                'submit' => array(
459
                    'title' => $this->l('Save'),
460
                ),
461
            ),
462
        );
463
    }
464
465
    /**
466
     * Form configuration function
467
     *
468
     * @param array $settings
469
     *
470
     * @return string
471
     */
472
    private function renderForm(array $settings)
473
    {
474
        $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...
475
        $helper->show_toolbar = false;
476
        $helper->table = $this->table;
477
        $helper->module = $this;
478
        $helper->default_form_language = $this->context->language->id;
479
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
480
        $helper->identifier = $this->identifier;
481
        $helper->submit_action = 'submit'.$this->name;
482
        $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...
483
        $helper->token = Tools::getAdminTokenLite('AdminModules');
484
        $helper->tpl_vars = array(
485
            'fields_value' => $settings,
486
            'languages' => $this->context->controller->getLanguages(),
487
            'id_language' => $this->context->language->id,
488
        );
489
490
        $helper->fields_value['pmt_url_ok'] = Configuration::get('pmt_url_ok');
491
492
        return $helper->generateForm(array($this->getConfigForm()));
493
    }
494
495
    /**
496
     * Function to update the variables of Paga+Tarde Module in the backoffice of prestashop
497
     *
498
     * @return string
499
     * @throws SmartyException
500
     */
501
    public function getContent()
502
    {
503
        $error = '';
504
        $message = '';
505
        $settings = array();
506
        $settings['pmt_public_key'] = Configuration::get('pmt_public_key');
507
        $settings['pmt_private_key'] = Configuration::get('pmt_private_key');
508
        $settingsKeys = array(
509
            'pmt_is_enabled',
510
            'pmt_public_key',
511
            'pmt_private_key',
512
            'pmt_simulator_is_enabled',
513
        );
514
515
        //Different Behavior depending on 1.6 or earlier
516
        if (Tools::isSubmit('submit'.$this->name)) {
517
            foreach ($settingsKeys as $key) {
518
                switch ($key) {
519
                    case 'pmt_public_key':
520
                        $value = Tools::getValue($key);
521
                        if (!$value) {
522
                            $error = $this->l('Please add a Paga+Tarde API Public Key');
523
                            break;
524
                        }
525
                        Configuration::updateValue($key, $value);
526
                        $settings[$key] = $value;
527
                        break;
528
                    case 'pmt_private_key':
529
                        $value = Tools::getValue($key);
530
                        if (!$value) {
531
                            $error = $this->l('Please add a Paga+Tarde API Private Key');
532
                            break;
533
                        }
534
                        Configuration::updateValue($key, $value);
535
                        $settings[$key] = $value;
536
                        break;
537
                    default:
538
                        $value = Tools::getValue($key);
539
                        Configuration::updateValue($key, $value);
540
                        $settings[$key] = $value;
541
                        break;
542
                }
543
                $message = $this->displayConfirmation($this->l('All changes have been saved'));
544
            }
545
        } else {
546
            foreach ($settingsKeys as $key) {
547
                    $settings[$key] = Configuration::get($key);
548
            }
549
        }
550
551
        if ($error) {
552
            $message = $this->displayError($error);
553
        }
554
555
        $logo = $this->getPathUri(). 'views/img/logo_pagamastarde.png';
556
        $tpl = $this->local_path.'views/templates/admin/config-info.tpl';
557
        $this->context->smarty->assign(array(
558
            'logo' => $logo,
559
            'form' => $this->renderForm($settings),
560
            'message' => $message,
561
            'version' => 'v'.$this->version,
562
        ));
563
564
        return $this->context->smarty->fetch($tpl);
565
    }
566
567
    /**
568
     * Hook to show payment method, this only applies on prestashop <= 1.6
569
     *
570
     * @param $params
571
     * @return bool | string
572
     * @throws Exception
573
     */
574
    public function hookPayment($params)
575
    {
576
        if (!$this->isPaymentMethodAvailable()) {
577
            return false;
578
        }
579
580
        /** @var Cart $cart */
581
        $cart                       = $params['cart'];
582
        $orderTotal                 = $cart->getOrderTotal();
583
        $link                       = $this->context->link;
584
        $pmtPublicKey               = Configuration::get('pmt_public_key');
585
        $pmtSimulatorIsEnabled      = Configuration::get('pmt_simulator_is_enabled');
586
        $pmtIsEnabled               = Configuration::get('pmt_is_enabled');
587
        $pmtSimulatorType           = Paylater::getExtraConfig('PMT_SIMULATOR_DISPLAY_TYPE');
588
        $pmtSimulatorCSSSelector    = Paylater::getExtraConfig('PMT_SIMULATOR_CSS_POSITION_SELECTOR');
589
        $pmtSimulatorPriceSelector  = Paylater::getExtraConfig('PMT_SIMULATOR_CSS_PRICE_SELECTOR');
590
        $pmtSimulatorQuotesStart    = Paylater::getExtraConfig('PMT_SIMULATOR_START_INSTALLMENTS');
591
        $pmtSimulatorSkin           = Paylater::getExtraConfig('PMT_SIMULATOR_DISPLAY_SKIN');
592
        $pmtSimulatorPosition       = Paylater::getExtraConfig('PMT_SIMULATOR_DISPLAY_CSS_POSITION');
593
        $pmtTitle                   = $this->l(Paylater::getExtraConfig('PMT_TITLE'));
594
        $this->context->smarty->assign($this->getButtonTemplateVars($cart));
595
        $this->context->smarty->assign(array(
596
            'amount'                => $orderTotal,
597
            'pmtPublicKey'          => $pmtPublicKey,
598
            'pmtCSSSelector'        => $pmtSimulatorCSSSelector,
599
            'pmtPriceSelector'      => $pmtSimulatorPriceSelector,
600
            'pmtQuotesStart'        => $pmtSimulatorQuotesStart,
601
            'pmtSimulatorIsEnabled' => $pmtSimulatorIsEnabled,
602
            'pmtSimulatorType'      => $pmtSimulatorType,
603
            'pmtSimulatorSkin'      => $pmtSimulatorSkin,
604
            'pmtSimulatorPosition'  => $pmtSimulatorPosition,
605
            'pmtIsEnabled'          => $pmtIsEnabled,
606
            'pmtTitle'              => $pmtTitle,
607
            'paymentUrl'            => $link->getModuleLink('paylater', 'payment'),
608
            '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...
609
        ));
610
611
        $supercheckout_enabled = Module::isEnabled('supercheckout');
612
        $onepagecheckoutps_enabled = Module::isEnabled('onepagecheckoutps');
613
        $onepagecheckout_enabled = Module::isEnabled('onepagecheckout');
614
615
        $return = true;
616
        if ($supercheckout_enabled || $onepagecheckout_enabled || $onepagecheckoutps_enabled) {
617
            $this->checkLogoExists();
618
            $return = $this->display(__FILE__, 'views/templates/hook/onepagecheckout.tpl');
619
        }
620
621
        if (_PS_VERSION_ < 1.7) {
622
            $return = $this->display(__FILE__, 'views/templates/hook/checkout-15.tpl');
623
        }
624
        return $return;
625
    }
626
627
    /**
628
     * @param string $functionName
629
     *
630
     * @return string
631
     * @throws PrestaShopDatabaseException
632
     * @throws PrestaShopException
633
     */
634
    public function productPageSimulatorDisplay($functionName)
635
    {
636
        $productConfiguration = Paylater::getExtraConfig('PMT_SIMULATOR_DISPLAY_POSITION');
637
        /** @var ProductCore $product */
638
        $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...
639
        $amount = $product->getPublicPrice();
640
        $pmtPublicKey                 = Configuration::get('pmt_public_key');
641
        $pmtSimulatorIsEnabled        = Configuration::get('pmt_simulator_is_enabled');
642
        $pmtIsEnabled                 = Configuration::get('pmt_is_enabled');
643
        $pmtSimulatorType             = Paylater::getExtraConfig('PMT_SIMULATOR_DISPLAY_TYPE');
644
        $pmtSimulatorCSSSelector      = Paylater::getExtraConfig('PMT_SIMULATOR_CSS_POSITION_SELECTOR');
645
        $pmtSimulatorPriceSelector    = Paylater::getExtraConfig('PMT_SIMULATOR_CSS_PRICE_SELECTOR');
646
        $pmtSimulatorQuantitySelector = Paylater::getExtraConfig('PMT_SIMULATOR_CSS_QUANTITY_SELECTOR');
647
        $pmtSimulatorQuotesStart      = Paylater::getExtraConfig('PMT_SIMULATOR_START_INSTALLMENTS');
648
        $pmtSimulatorSkin             = Paylater::getExtraConfig('PMT_SIMULATOR_DISPLAY_SKIN');
649
        $pmtSimulatorPosition         = Paylater::getExtraConfig('PMT_SIMULATOR_DISPLAY_CSS_POSITION');
650
        $pmtDisplayMinAmount          = Paylater::getExtraConfig('PMT_DISPLAY_MIN_AMOUNT');
651
652
        if ($functionName != $productConfiguration ||
653
            $amount <= 0 ||
654
            $amount < $pmtDisplayMinAmount ||
655
            !$pmtSimulatorType
656
        ) {
657
            return null;
658
        }
659
660
        $this->context->smarty->assign(array(
661
            'amount'                => $amount,
662
            'pmtPublicKey'          => $pmtPublicKey,
663
            'pmtCSSSelector'        => $pmtSimulatorCSSSelector,
664
            'pmtPriceSelector'      => $pmtSimulatorPriceSelector,
665
            'pmtQuantitySelector'   => $pmtSimulatorQuantitySelector,
666
            'pmtSimulatorIsEnabled' => $pmtSimulatorIsEnabled,
667
            'pmtIsEnabled'          => $pmtIsEnabled,
668
            'pmtSimulatorType'      => $pmtSimulatorType,
669
            'pmtSimulatorSkin'      => $pmtSimulatorSkin,
670
            'pmtSimulatorPosition'  => $pmtSimulatorPosition,
671
            'pmtQuotesStart'        => $pmtSimulatorQuotesStart,
672
        ));
673
674
        return $this->display(__FILE__, 'views/templates/hook/product-simulator.tpl');
675
    }
676
677
    /**
678
     * @return string
679
     * @throws PrestaShopDatabaseException
680
     * @throws PrestaShopException
681
     */
682
    public function hookDisplayRightColumn()
683
    {
684
685
        return $this->productPageSimulatorDisplay(__FUNCTION__);
686
    }
687
688
    /**
689
     * @return string
690
     * @throws PrestaShopDatabaseException
691
     * @throws PrestaShopException
692
     */
693
    public function hookDisplayLeftColumn()
694
    {
695
        return $this->productPageSimulatorDisplay(__FUNCTION__);
696
    }
697
698
    /**
699
     * @return string
700
     * @throws PrestaShopDatabaseException
701
     * @throws PrestaShopException
702
     */
703
    public function hookDisplayRightColumnProduct()
704
    {
705
        return $this->productPageSimulatorDisplay(__FUNCTION__);
706
    }
707
708
    /**
709
     * @return string
710
     * @throws PrestaShopDatabaseException
711
     * @throws PrestaShopException
712
     */
713
    public function hookDisplayLeftColumnProduct()
714
    {
715
        return $this->productPageSimulatorDisplay(__FUNCTION__);
716
    }
717
718
    /**
719
     * @return string
720
     * @throws PrestaShopDatabaseException
721
     * @throws PrestaShopException
722
     */
723
    public function hookDisplayProductButtons()
724
    {
725
        return $this->productPageSimulatorDisplay(__FUNCTION__);
726
    }
727
728
    /**
729
     * @param array $params
730
     *
731
     * @return string
732
     */
733
    public function hookDisplayOrderConfirmation($params)
734
    {
735
        $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...
736
737
        if ($paymentMethod == $this->displayName) {
738
            return $this->display(__FILE__, 'views/templates/hook/payment-return.tpl');
739
        }
740
741
        return null;
742
    }
743
744
    /**
745
     * Check logo exists in OPC module
746
     */
747
    public function checkLogoExists()
748
    {
749
        $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...
750
        if (!file_exists($logo) && is_dir(_PS_MODULE_DIR_ . '/onepagecheckoutps/views/img/payments')) {
751
            copy(
752
                _PS_PAYLATER_DIR . '/views/img/logo-64x64.png',
753
                $logo
754
            );
755
        }
756
    }
757
758
    public static function getExtraConfig($config = null, $default = '')
759
    {
760
        if (is_null($config)) {
761
            return '';
762
        }
763
764
        $sql = 'SELECT value FROM '._DB_PREFIX_.'pmt_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

764
        $sql = 'SELECT value FROM '._DB_PREFIX_.'pmt_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...
765
        if ($results = Db::getInstance()->ExecuteS($sql)) {
766
            if (is_array($results) && count($results) === 1 && isset($results[0]['value'])) {
767
                return $results[0]['value'];
768
            }
769
        }
770
771
        return $default;
772
    }
773
}
774