Passed
Pull Request — master (#28)
by Raúl
03:10
created

Paylater::uninstall()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 4
b 0
f 0
nc 1
nop 0
dl 0
loc 5
rs 10
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
     * @var array
40
     */
41
    public $dotEnvError = null;
42
43
    /**
44
     * Default module advanced configuration values
45
     *
46
     * @var array
47
     */
48
    public $defaultConfigs = array(
49
        'PMT_TITLE' => 'Instant Financing',
50
        'PMT_SIMULATOR_DISPLAY_TYPE' => 'pmtSDK.simulator.types.SIMPLE',
51
        'PMT_SIMULATOR_DISPLAY_SKIN' => 'pmtSDK.simulator.skins.BLUE',
52
        'PMT_SIMULATOR_DISPLAY_POSITION' => 'hookDisplayProductButtons',
53
        'PMT_SIMULATOR_START_INSTALLMENTS' => '3',
54
        'PMT_SIMULATOR_CSS_POSITION_SELECTOR' => 'default',
55
        'PMT_SIMULATOR_DISPLAY_CSS_POSITION' => 'pmtSDK.simulator.positions.INNER',
56
        'PMT_SIMULATOR_CSS_PRICE_SELECTOR' => 'default',
57
        'PMT_SIMULATOR_CSS_QUANTITY_SELECTOR' => 'default',
58
        'PMT_FORM_DISPLAY_TYPE' => '0',
59
        'PMT_DISPLAY_MIN_AMOUNT' => '1',
60
        'PMT_URL_OK' => '',
61
        'PMT_URL_KO' => '',
62
    );
63
64
    /**
65
     * Paylater constructor.
66
     *
67
     * Define the module main properties so that prestashop understands what are the module requirements
68
     * and how to manage the module.
69
     *
70
     */
71
    public function __construct()
72
    {
73
        $this->dotEnvError = null;
74
        $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...
75
        $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...
76
        $this->version = '7.2.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...
77
        $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...
78
        $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...
79
        $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...
80
        $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...
81
        $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...
82
        $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...
83
        $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...
84
            'Instant, easy and effective financial tool for your customers'
85
        );
86
87
        $sql_file = dirname(__FILE__).'/sql/install.sql';
88
        $this->loadSQLFile($sql_file);
89
90
        $this->loadEnvVariables();
91
92
        //migrate data from old modules to 7x generation
93
        $this->migrate();
94
95
        $this->checkHooks();
96
97
        parent::__construct();
98
    }
99
100
    /**
101
     * Configure the variables for paga+tarde payment method.
102
     *
103
     * @return bool
104
     */
105
    public function install()
106
    {
107
        if (!extension_loaded('curl')) {
108
            $this->installErrors[] =
109
                $this->l('You have to enable the cURL extension on your server to install this module');
110
            return false;
111
        }
112
        if (!version_compare(phpversion(), '5.3.0', '>=')) {
113
            $this->installErrors[] = $this->l('The PHP version bellow 5.3.0 is not supported');
114
            return false;
115
        }
116
        $curl_info = curl_version();
117
        $curl_version = $curl_info['version'];
118
        if (!version_compare($curl_version, '7.34.0', '>=')) {
119
            $this->installErrors[] = $this->l('Curl Version is lower than 7.34.0 and does not support TLS 1.2');
120
            return false;
121
        }
122
123
        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...
124
        Configuration::updateValue('pmt_simulator_is_enabled', 1);
125
        Configuration::updateValue('pmt_public_key', '');
126
        Configuration::updateValue('pmt_private_key', '');
127
128
        return (parent::install()
129
            && $this->registerHook('displayShoppingCart')
130
            && $this->registerHook('payment')
131
            && $this->registerHook('paymentOptions')
132
            && $this->registerHook('displayRightColumn')
133
            && $this->registerHook('displayLeftColumn')
134
            && $this->registerHook('displayRightColumnProduct')
135
            && $this->registerHook('displayLeftColumnProduct')
136
            && $this->registerHook('displayProductButtons')
137
            && $this->registerHook('displayOrderConfirmation')
138
            && $this->registerHook('header')
139
        );
140
    }
141
142
    /**
143
     * Remove the production private api key and remove the files
144
     *
145
     * @return bool
146
     */
147
    public function uninstall()
148
    {
149
        Configuration::deleteByName('PAYLATER_PRIVATE_KEY_PROD');
150
151
        return parent::uninstall();
152
    }
153
154
    /**
155
     * Migrate the configs of older veresions < 7x to new configurations
156
     */
157
    public function migrate()
158
    {
159
        // If this configuration exists is because we came form a version lower than 7.x
160
        if (Configuration::get('PAYLATER_MIN_AMOUNT')) {
161
            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...
162
                'pmt_config',
163
                array('value' => Configuration::get('PAYLATER_MIN_AMOUNT')),
164
                'config = \'PMT_DISPLAY_MIN_AMOUNT\''
165
            );
166
            Configuration::updateValue('PAYLATER_MIN_AMOUNT', false);
167
            Configuration::updateValue('pmt_is_enabled', 1);
168
            Configuration::updateValue('pmt_simulator_is_enabled', 1);
169
170
            // migrating pk/tk from previous version
171
            if (Configuration::get('pmt_public_key') === false
172
                && Configuration::get('PAYLATER_PUBLIC_KEY_PROD')
173
            ) {
174
                Configuration::updateValue('pmt_public_key', Configuration::get('PAYLATER_PUBLIC_KEY_PROD'));
175
                Configuration::updateValue('PAYLATER_PUBLIC_KEY_PROD', false);
176
            } elseif (Configuration::get('pmt_public_key') === false
177
                && Configuration::get('PAYLATER_PUBLIC_KEY_TEST')
178
            ) {
179
                Configuration::updateValue('pmt_public_key', Configuration::get('PAYLATER_PUBLIC_KEY_TEST'));
180
                Configuration::updateValue('PAYLATER_PUBLIC_KEY_TEST', false);
181
            }
182
183
            if (Configuration::get('pmt_private_key') === false
184
                && Configuration::get('PAYLATER_PRIVATE_KEY_PROD')
185
            ) {
186
                Configuration::updateValue('pmt_private_key', Configuration::get('PAYLATER_PRIVATE_KEY_PROD'));
187
                Configuration::updateValue('PAYLATER_PRIVATE_KEY_PROD', false);
188
            } elseif (Configuration::get('pmt_private_key') === false
189
                && Configuration::get('PAYLATER_PRIVATE_KEY_TEST')
190
            ) {
191
                Configuration::updateValue('pmt_private_key', Configuration::get('PAYLATER_PRIVATE_KEY_TEST'));
192
                Configuration::updateValue('PAYLATER_PRIVATE_KEY_TEST', false);
193
            }
194
        }
195
    }
196
197
    /**
198
     * Check if new hooks used in new 7x versions are enabled and activate them if needed
199
     *
200
     * @throws PrestaShopDatabaseException
201
     */
202
    public function checkHooks()
203
    {
204
        try {
205
            $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...
206
            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...
207
            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...
208
            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...
209
            $hook_exists = Db::getInstance()->ExecuteS($sql_content);
210
            if (empty($hook_exists)) {
211
                $sql_insert = 'insert into ' . _DB_PREFIX_.  'hook_module 
212
            (id_module, id_shop, id_hook, position)
213
            values
214
            (\''. Module::getModuleIdByName($this->name) . '\',
215
            \''. Shop::getContextShopID() . '\',
216
            \''. Hook::getIdByName('header') . '\',
217
            150)';
218
                Db::getInstance()->execute($sql_insert);
219
            }
220
        } catch (\Exception $exception) {
221
            //continue without errors
222
        }
223
    }
224
225
    public function loadEnvVariables()
226
    {
227
        $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...
228
        $dbConfigs = Db::getInstance()->executeS($sql_content);
229
230
        // Convert a multimple dimension array for SQL insert statements into a simple key/value
231
        $simpleDbConfigs = array();
232
        foreach ($dbConfigs as $config) {
233
            $simpleDbConfigs[$config['config']] = $config['value'];
234
        }
235
        $newConfigs = array_diff_key($this->defaultConfigs, $simpleDbConfigs);
236
        if (!empty($newConfigs)) {
237
            $data = array();
238
            foreach ($newConfigs as $key => $value) {
239
                $data[] = array(
240
                    'config' => $key,
241
                    'value' => $value,
242
                );
243
            }
244
            Db::getInstance()->insert('pmt_config', $data);
245
        }
246
247
        foreach (array_merge($this->defaultConfigs, $simpleDbConfigs) as $key => $value) {
248
            putenv($key . '=' . $value);
249
        }
250
251
        // Save defaultOptions as a env varible to have it in configController
252
        putenv("PMT_DEFAULT_CONFIGS" . '=' . json_encode($this->defaultConfigs));
253
    }
254
255
    /**
256
     * @param $sql_file
257
     * @return bool
258
     */
259
    public function loadSQLFile($sql_file)
260
    {
261
        $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...
262
263
        // Replace prefix and store SQL command in array
264
        $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...
265
        $sql_requests = preg_split("/;\s*[\r\n]+/", $sql_content);
266
267
        $result = true;
268
        foreach ($sql_requests as $request) {
269
            if (!empty($request)) {
270
                $result &= Db::getInstance()->execute(trim($request));
271
            }
272
        }
273
274
        // Return result
275
        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...
276
    }
277
278
    /**
279
     * Check amount of order > minAmount
280
     * Check valid currency
281
     * Check API variables are set
282
     *
283
     * @return bool
284
     * @throws PrestaShopDatabaseException
285
     * @throws PrestaShopException
286
     */
287
    public function isPaymentMethodAvailable()
288
    {
289
        $cart                       = $this->context->cart;
290
        $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...
291
        $availableCurrencies        = array('EUR');
292
        $pmtDisplayMinAmount        = getenv('PMT_DISPLAY_MIN_AMOUNT');
293
        $pmtPublicKey               = Configuration::get('pmt_public_key');
294
        $pmtPrivateKey              = Configuration::get('pmt_private_key');
295
296
        return (
297
            $cart->getOrderTotal() >= $pmtDisplayMinAmount &&
298
            in_array($currency->iso_code, $availableCurrencies) &&
299
            $pmtPublicKey &&
300
            $pmtPrivateKey
301
        );
302
    }
303
304
    /**
305
     * @param Cart $cart
306
     *
307
     * @return array
308
     * @throws Exception
309
     */
310
    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...
311
    {
312
        $currency = new Currency(($cart->id_currency));
313
314
        return array(
315
            'paylater_button' => '#paylater_payment_button',
316
            'paylater_currency_iso' => $currency->iso_code,
317
            'paylater_cart_total' => $cart->getOrderTotal(),
318
        );
319
    }
320
321
    /**
322
     * Header hook
323
     */
324
    public function hookHeader()
325
    {
326
        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...
327
            $this->context->controller->registerJavascript(
328
                sha1(mt_rand(1, 90000)),
329
                'http://cdn.pagamastarde.com/js/pmt-v2/sdk.js',
330
                array('server' => 'remote')
331
            );
332
        } else {
333
            $this->context->controller->addJS('http://cdn.pagamastarde.com/js/pmt-v2/sdk.js');
334
        }
335
        $this->context->controller->addJS($this->getPathUri(). 'views/js/simulator.js');
336
    }
337
338
    /**
339
     * @return array
340
     * @throws Exception
341
     */
342
    public function hookPaymentOptions()
343
    {
344
        if (!$this->isPaymentMethodAvailable()) {
345
            return array();
346
        }
347
348
        /** @var Cart $cart */
349
        $cart                       = $this->context->cart;
350
        $orderTotal                 = $cart->getOrderTotal();
351
        $link                       = $this->context->link;
352
        $pmtPublicKey               = Configuration::get('pmt_public_key');
353
        $pmtSimulatorIsEnabled      = Configuration::get('pmt_simulator_is_enabled');
354
        $pmtIsEnabled               = Configuration::get('pmt_is_enabled');
355
        $pmtSimulatorType           = getenv('PMT_SIMULATOR_DISPLAY_TYPE');
356
        $pmtSimulatorCSSSelector    = getenv('PMT_SIMULATOR_CSS_POSITION_SELECTOR');
357
        $pmtSimulatorPriceSelector  = getenv('PMT_SIMULATOR_CSS_PRICE_SELECTOR');
358
        $pmtSimulatorQuotesStart    = getenv('PMT_SIMULATOR_START_INSTALLMENTS');
359
        $pmtSimulatorSkin           = getenv('PMT_SIMULATOR_DISPLAY_SKIN');
360
        $pmtSimulatorPosition       = getenv('PMT_SIMULATOR_DISPLAY_CSS_POSITION');
361
        $pmtTitle                   = $this->l(getenv('PMT_TITLE'));
362
363
        $this->context->smarty->assign($this->getButtonTemplateVars($cart));
364
        $this->context->smarty->assign(array(
365
            'amount'                => $orderTotal,
366
            'pmtPublicKey'          => $pmtPublicKey,
367
            'pmtCSSSelector'        => $pmtSimulatorCSSSelector,
368
            'pmtPriceSelector'      => $pmtSimulatorPriceSelector,
369
            'pmtQuotesStart'        => $pmtSimulatorQuotesStart,
370
            'pmtSimulatorIsEnabled' => $pmtSimulatorIsEnabled,
371
            'pmtSimulatorType'      => $pmtSimulatorType,
372
            'pmtSimulatorSkin'      => $pmtSimulatorSkin,
373
            'pmtSimulatorPosition'  => $pmtSimulatorPosition,
374
            'pmtIsEnabled'          => $pmtIsEnabled,
375
            'pmtTitle'              => $pmtTitle,
376
            'paymentUrl'            => $link->getModuleLink('paylater', 'payment'),
377
            '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...
378
        ));
379
380
        $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...
381
        $paymentOption
382
            ->setCallToActionText($pmtTitle)
383
            ->setAction($link->getModuleLink('paylater', 'payment'))
384
            ->setLogo($this->getPathUri(). 'logo.gif')
385
            ->setModuleName(__CLASS__)
386
        ;
387
388
389
        if (_PS_VERSION_ < 1.7) {
390
            $paymentOption->setAdditionalInformation(
391
                $this->fetch('module:paylater/views/templates/hook/checkout-15.tpl')
392
            );
393
        }
394
395
        return array($paymentOption);
396
    }
397
398
    /**
399
     * Get the form for editing the BackOffice options of the module
400
     *
401
     * @return array
402
     */
403
    private function getConfigForm()
404
    {
405
        return array(
406
            'form' => array(
407
                'legend' => array(
408
                    'title' => $this->l('Basic Settings'),
409
                    'icon' => 'icon-cogs',
410
                ),
411
                'input' => array(
412
                    array(
413
                        'name' => 'pmt_is_enabled',
414
                        '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...
415
                        'label' => $this->l('Module is enabled'),
416
                        'prefix' => '<i class="icon icon-key"></i>',
417
                        'class' => 't',
418
                        'required' => true,
419
                        'values'=> array(
420
                            array(
421
                                'id' => 'pmt_is_enabled_true',
422
                                'value' => 1,
423
                                'label' => $this->l('Yes', get_class($this), null, false),
424
                            ),
425
                            array(
426
                                'id' => 'pmt_is_enabled_false',
427
                                'value' => 0,
428
                                'label' => $this->l('No', get_class($this), null, false),
429
                            ),
430
                        )
431
                    ),
432
                    array(
433
                        'name' => 'pmt_public_key',
434
                        'suffix' => $this->l('ex: pk_fd53cd467ba49022e4gf215e'),
435
                        'type' => 'text',
436
                        'size' => 60,
437
                        'label' => $this->l('Public Key'),
438
                        'prefix' => '<i class="icon icon-key"></i>',
439
                        'col' => 6,
440
                        'required' => true,
441
                    ),
442
                    array(
443
                        'name' => 'pmt_private_key',
444
                        'suffix' => $this->l('ex: 21e5723a97459f6a'),
445
                        'type' => 'text',
446
                        'size' => 60,
447
                        'label' => $this->l('Secret Key'),
448
                        'prefix' => '<i class="icon icon-key"></i>',
449
                        'col' => 6,
450
                        'required' => true,
451
                    ),
452
                    array(
453
                        'name' => 'pmt_simulator_is_enabled',
454
                        'type' => (version_compare(_PS_VERSION_, '1.6')<0) ?'radio' :'switch',
455
                        'label' => $this->l('Simulator is enabled'),
456
                        'prefix' => '<i class="icon icon-key"></i>',
457
                        'class' => 't',
458
                        'required' => true,
459
                        'values'=> array(
460
                            array(
461
                                'id' => 'pmt_simulator_is_enabled_on',
462
                                'value' => 1,
463
                                'label' => $this->l('Yes'),
464
                            ),
465
                            array(
466
                                'id' => 'pmt_simulator_is_enabled_off',
467
                                'value' => 0,
468
                                'label' => $this->l('No'),
469
                            ),
470
                        )
471
                    ),
472
                ),
473
                'submit' => array(
474
                    'title' => $this->l('Save'),
475
                ),
476
            ),
477
        );
478
    }
479
480
    /**
481
     * Form configuration function
482
     *
483
     * @param array $settings
484
     *
485
     * @return string
486
     */
487
    private function renderForm(array $settings)
488
    {
489
        $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...
490
        $helper->show_toolbar = false;
491
        $helper->table = $this->table;
492
        $helper->module = $this;
493
        $helper->default_form_language = $this->context->language->id;
494
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
495
        $helper->identifier = $this->identifier;
496
        $helper->submit_action = 'submit'.$this->name;
497
        $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...
498
        $helper->token = Tools::getAdminTokenLite('AdminModules');
499
        $helper->tpl_vars = array(
500
            'fields_value' => $settings,
501
            'languages' => $this->context->controller->getLanguages(),
502
            'id_language' => $this->context->language->id,
503
        );
504
505
        $helper->fields_value['pmt_url_ok'] = Configuration::get('pmt_url_ok');
506
507
        return $helper->generateForm(array($this->getConfigForm()));
508
    }
509
510
    /**
511
     * Function to update the variables of Paga+Tarde Module in the backoffice of prestashop
512
     *
513
     * @return string
514
     * @throws SmartyException
515
     */
516
    public function getContent()
517
    {
518
        $error = '';
519
        $message = '';
520
        $settings = array();
521
        $settings['pmt_public_key'] = Configuration::get('pmt_public_key');
522
        $settings['pmt_private_key'] = Configuration::get('pmt_private_key');
523
        $settingsKeys = array(
524
            'pmt_is_enabled',
525
            'pmt_public_key',
526
            'pmt_private_key',
527
            'pmt_simulator_is_enabled',
528
        );
529
530
        //Different Behavior depending on 1.6 or earlier
531
        if (Tools::isSubmit('submit'.$this->name)) {
532
            foreach ($settingsKeys as $key) {
533
                switch ($key) {
534
                    case 'pmt_public_key':
535
                        $value = Tools::getValue($key);
536
                        if (!$value) {
537
                            $error = $this->l('Please add a Paga+Tarde API Public Key');
538
                            break;
539
                        }
540
                        Configuration::updateValue($key, $value);
541
                        $settings[$key] = $value;
542
                        break;
543
                    case 'pmt_private_key':
544
                        $value = Tools::getValue($key);
545
                        if (!$value) {
546
                            $error = $this->l('Please add a Paga+Tarde API Private Key');
547
                            break;
548
                        }
549
                        Configuration::updateValue($key, $value);
550
                        $settings[$key] = $value;
551
                        break;
552
                    default:
553
                        $value = Tools::getValue($key);
554
                        Configuration::updateValue($key, $value);
555
                        $settings[$key] = $value;
556
                        break;
557
                }
558
                $message = $this->displayConfirmation($this->l('All changes have been saved'));
559
            }
560
        } else {
561
            foreach ($settingsKeys as $key) {
562
                    $settings[$key] = Configuration::get($key);
563
            }
564
        }
565
566
        if ($error) {
567
            $message = $this->displayError($error);
568
        }
569
        if ($this->dotEnvError) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->dotEnvError of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
570
            $message = $this->displayError($this->dotEnvError);
571
        }
572
573
        $logo = $this->getPathUri(). 'views/img/logo_pagamastarde.png';
574
        $tpl = $this->local_path.'views/templates/admin/config-info.tpl';
575
        $this->context->smarty->assign(array(
576
            'logo' => $logo,
577
            'form' => $this->renderForm($settings),
578
            'message' => $message,
579
            'version' => 'v'.$this->version,
580
        ));
581
582
        return $this->context->smarty->fetch($tpl);
583
    }
584
585
    /**
586
     * Hook to show payment method, this only applies on prestashop <= 1.6
587
     *
588
     * @param $params
589
     * @return bool | string
590
     * @throws Exception
591
     */
592
    public function hookPayment($params)
593
    {
594
        if (!$this->isPaymentMethodAvailable()) {
595
            return false;
596
        }
597
598
        /** @var Cart $cart */
599
        $cart                       = $params['cart'];
600
        $orderTotal                 = $cart->getOrderTotal();
601
        $link                       = $this->context->link;
602
        $pmtPublicKey               = Configuration::get('pmt_public_key');
603
        $pmtSimulatorIsEnabled      = Configuration::get('pmt_simulator_is_enabled');
604
        $pmtIsEnabled               = Configuration::get('pmt_is_enabled');
605
        $pmtSimulatorType           = getenv('PMT_SIMULATOR_DISPLAY_TYPE');
606
        $pmtSimulatorCSSSelector    = getenv('PMT_SIMULATOR_CSS_POSITION_SELECTOR');
607
        $pmtSimulatorPriceSelector  = getenv('PMT_SIMULATOR_CSS_PRICE_SELECTOR');
608
        $pmtSimulatorQuotesStart    = getenv('PMT_SIMULATOR_START_INSTALLMENTS');
609
        $pmtSimulatorSkin           = getenv('PMT_SIMULATOR_DISPLAY_SKIN');
610
        $pmtSimulatorPosition       = getenv('PMT_SIMULATOR_DISPLAY_CSS_POSITION');
611
        $pmtTitle                   = $this->l(getenv('PMT_TITLE'));
612
        $this->context->smarty->assign($this->getButtonTemplateVars($cart));
613
        $this->context->smarty->assign(array(
614
            'amount'                => $orderTotal,
615
            'pmtPublicKey'          => $pmtPublicKey,
616
            'pmtCSSSelector'        => $pmtSimulatorCSSSelector,
617
            'pmtPriceSelector'      => $pmtSimulatorPriceSelector,
618
            'pmtQuotesStart'        => $pmtSimulatorQuotesStart,
619
            'pmtSimulatorIsEnabled' => $pmtSimulatorIsEnabled,
620
            'pmtSimulatorType'      => $pmtSimulatorType,
621
            'pmtSimulatorSkin'      => $pmtSimulatorSkin,
622
            'pmtSimulatorPosition'  => $pmtSimulatorPosition,
623
            'pmtIsEnabled'          => $pmtIsEnabled,
624
            'pmtTitle'              => $pmtTitle,
625
            'paymentUrl'            => $link->getModuleLink('paylater', 'payment'),
626
            '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...
627
        ));
628
629
        $supercheckout_enabled = Module::isEnabled('supercheckout');
630
        $onepagecheckoutps_enabled = Module::isEnabled('onepagecheckoutps');
631
        $onepagecheckout_enabled = Module::isEnabled('onepagecheckout');
632
633
        $return = true;
634
        if ($supercheckout_enabled || $onepagecheckout_enabled || $onepagecheckoutps_enabled) {
635
            $this->checkLogoExists();
636
            $return = $this->display(__FILE__, 'views/templates/hook/onepagecheckout.tpl');
637
        }
638
639
        if (_PS_VERSION_ < 1.7) {
640
            $return = $this->display(__FILE__, 'views/templates/hook/checkout-15.tpl');
641
        }
642
        return $return;
643
    }
644
645
    /**
646
     * @param string $functionName
647
     *
648
     * @return string
649
     * @throws PrestaShopDatabaseException
650
     * @throws PrestaShopException
651
     */
652
    public function productPageSimulatorDisplay($functionName)
653
    {
654
        $productConfiguration = getenv('PMT_SIMULATOR_DISPLAY_POSITION');
655
        /** @var ProductCore $product */
656
        $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...
657
        $amount = $product->getPublicPrice();
658
        $pmtPublicKey                = Configuration::get('pmt_public_key');
659
        $pmtSimulatorIsEnabled        = Configuration::get('pmt_simulator_is_enabled');
660
        $pmtIsEnabled                 = Configuration::get('pmt_is_enabled');
661
        $pmtSimulatorType             = getenv('PMT_SIMULATOR_DISPLAY_TYPE');
662
        $pmtSimulatorCSSSelector      = getenv('PMT_SIMULATOR_CSS_POSITION_SELECTOR');
663
        $pmtSimulatorPriceSelector    = getenv('PMT_SIMULATOR_CSS_PRICE_SELECTOR');
664
        $pmtSimulatorQuantitySelector = getenv('PMT_SIMULATOR_CSS_QUANTITY_SELECTOR');
665
        $pmtSimulatorQuotesStart      = getenv('PMT_SIMULATOR_START_INSTALLMENTS');
666
        $pmtSimulatorSkin             = getenv('PMT_SIMULATOR_DISPLAY_SKIN');
667
        $pmtSimulatorPosition         = getenv('PMT_SIMULATOR_DISPLAY_CSS_POSITION');
668
        $pmtDisplayMinAmount          = getenv('PMT_DISPLAY_MIN_AMOUNT');
669
670
        if ($functionName != $productConfiguration ||
671
            $amount <= 0 ||
672
            $amount < $pmtDisplayMinAmount ||
673
            !$pmtSimulatorType
674
        ) {
675
            return null;
676
        }
677
678
        $this->context->smarty->assign(array(
679
            'amount'                => $amount,
680
            'pmtPublicKey'          => $pmtPublicKey,
681
            'pmtCSSSelector'        => $pmtSimulatorCSSSelector,
682
            'pmtPriceSelector'      => $pmtSimulatorPriceSelector,
683
            'pmtQuantitySelector'   => $pmtSimulatorQuantitySelector,
684
            'pmtSimulatorIsEnabled' => $pmtSimulatorIsEnabled,
685
            'pmtIsEnabled'          => $pmtIsEnabled,
686
            'pmtSimulatorType'      => $pmtSimulatorType,
687
            'pmtSimulatorSkin'      => $pmtSimulatorSkin,
688
            'pmtSimulatorPosition'  => $pmtSimulatorPosition,
689
            'pmtQuotesStart'        => $pmtSimulatorQuotesStart,
690
        ));
691
692
        return $this->display(__FILE__, 'views/templates/hook/product-simulator.tpl');
693
    }
694
695
    /**
696
     * @return string
697
     * @throws PrestaShopDatabaseException
698
     * @throws PrestaShopException
699
     */
700
    public function hookDisplayRightColumn()
701
    {
702
703
        return $this->productPageSimulatorDisplay(__FUNCTION__);
704
    }
705
706
    /**
707
     * @return string
708
     * @throws PrestaShopDatabaseException
709
     * @throws PrestaShopException
710
     */
711
    public function hookDisplayLeftColumn()
712
    {
713
        return $this->productPageSimulatorDisplay(__FUNCTION__);
714
    }
715
716
    /**
717
     * @return string
718
     * @throws PrestaShopDatabaseException
719
     * @throws PrestaShopException
720
     */
721
    public function hookDisplayRightColumnProduct()
722
    {
723
        return $this->productPageSimulatorDisplay(__FUNCTION__);
724
    }
725
726
    /**
727
     * @return string
728
     * @throws PrestaShopDatabaseException
729
     * @throws PrestaShopException
730
     */
731
    public function hookDisplayLeftColumnProduct()
732
    {
733
        return $this->productPageSimulatorDisplay(__FUNCTION__);
734
    }
735
736
    /**
737
     * @return string
738
     * @throws PrestaShopDatabaseException
739
     * @throws PrestaShopException
740
     */
741
    public function hookDisplayProductButtons()
742
    {
743
        return $this->productPageSimulatorDisplay(__FUNCTION__);
744
    }
745
746
    /**
747
     * @param array $params
748
     *
749
     * @return string
750
     */
751
    public function hookDisplayOrderConfirmation($params)
752
    {
753
        $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...
754
755
        if ($paymentMethod == $this->displayName) {
756
            return $this->display(__FILE__, 'views/templates/hook/payment-return.tpl');
757
        }
758
759
        return null;
760
    }
761
762
    /**
763
     * Check logo exists in OPC module
764
     */
765
    public function checkLogoExists()
766
    {
767
        $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...
768
        if (!file_exists($logo) && is_dir(_PS_MODULE_DIR_ . '/onepagecheckoutps/views/img/payments')) {
769
            copy(
770
                _PS_PAYLATER_DIR . '/views/img/logo-64x64.png',
771
                $logo
772
            );
773
        }
774
    }
775
}
776