1<?php
2/**
3 * 2007-2016 PrestaShop
4 *
5 * thirty bees is an extension to the PrestaShop e-commerce software developed by PrestaShop SA
6 * Copyright (C) 2017-2018 thirty bees
7 *
8 * NOTICE OF LICENSE
9 *
10 * This source file is subject to the Open Software License (OSL 3.0)
11 * that is bundled with this package in the file LICENSE.txt.
12 * It is also available through the world-wide-web at this URL:
13 * http://opensource.org/licenses/osl-3.0.php
14 * If you did not receive a copy of the license and are unable to
15 * obtain it through the world-wide-web, please send an email
16 * to license@thirtybees.com so we can send you a copy immediately.
17 *
18 * DISCLAIMER
19 *
20 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
21 * versions in the future. If you wish to customize PrestaShop for your
22 * needs please refer to https://www.thirtybees.com for more information.
23 *
24 *  @author    thirty bees <contact@thirtybees.com>
25 *  @author    PrestaShop SA <contact@prestashop.com>
26 *  @copyright 2017-2018 thirty bees
27 *  @copyright 2007-2016 PrestaShop SA
28 *  @license   http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
29 *  PrestaShop is an internationally registered trademark & property of PrestaShop SA
30 */
31
32/**
33 * Class AdminPaymentControllerCore
34 *
35 * @since 1.0.0
36 */
37class AdminPaymentControllerCore extends AdminController
38{
39    // @codingStandardsIgnoreStart
40    /** @var array $payment_modules */
41    public $payment_modules = [];
42    // @codingStandardsIgnoreEnd
43
44    /**
45     * AdminPaymentControllerCore constructor.
46     *
47     * @since   1.0.0
48     * @version 1.0.0 Initial version
49     */
50    public function __construct()
51    {
52        $this->bootstrap = true;
53        parent::__construct();
54
55        $idShop = $this->context->shop->id;
56
57        /* Get all modules then select only payment ones */
58        $modules = Module::getModulesOnDisk(true);
59
60        foreach ($modules as $module) {
61            if ($module->tab == 'payments_gateways') {
62                if ($module->id) {
63                    if (!get_class($module) == 'SimpleXMLElement') {
64                        $module->country = [];
65                    }
66                    $sql = new DbQuery();
67                    $sql->select('`id_country`');
68                    $sql->from('module_country');
69                    $sql->where('`id_module` = '.(int) $module->id);
70                    $sql->where('`id_shop` = '.(int) $idShop);
71
72                    $countries = DB::getInstance()->executeS($sql);
73                    foreach ($countries as $country) {
74                        $module->country[] = $country['id_country'];
75                    }
76
77                    if (!get_class($module) == 'SimpleXMLElement') {
78                        $module->currency = [];
79                    }
80                    $sql = new DbQuery();
81                    $sql->select('`id_currency`');
82                    $sql->from('module_currency');
83                    $sql->where('`id_module` = '.(int) $module->id);
84                    $sql->where('`id_shop` = '.(int) $idShop);
85
86                    $currencies = DB::getInstance()->executeS($sql);
87                    foreach ($currencies as $currency) {
88                        $module->currency[] = $currency['id_currency'];
89                    }
90
91                    if (!get_class($module) == 'SimpleXMLElement') {
92                        $module->group = [];
93                    }
94                    $sql = new DbQuery();
95                    $sql->select('`id_group`');
96                    $sql->from('module_group');
97                    $sql->where('`id_module` = '.(int) $module->id);
98                    $sql->where('`id_shop` = '.(int) $idShop);
99
100                    $groups = DB::getInstance()->executeS($sql);
101                    foreach ($groups as $group) {
102                        $module->group[] = $group['id_group'];
103                    }
104
105                    if (!get_class($module) == 'SimpleXMLElement') {
106                        $module->reference = array();
107                    }
108                    $sql = new DbQuery();
109                    $sql->select('`id_reference`');
110                    $sql->from('module_carrier');
111                    $sql->where('`id_module` = '.(int) $module->id);
112                    $sql->where('`id_shop` = '.(int) $idShop);
113
114                    $carriers = Db::getInstance()->executeS($sql);
115                    foreach ($carriers as $carrier) {
116                        $module->reference[] = $carrier['id_reference'];
117                    }
118                } else {
119                    $module->country = null;
120                    $module->currency = null;
121                    $module->group = null;
122                    $module->reference = null;
123                }
124
125                $this->payment_modules[] = $module;
126            }
127        }
128    }
129
130    /**
131     * @since   1.0.0
132     * @version 1.0.0 Initial version
133     */
134    public function initToolbarTitle()
135    {
136        $this->toolbar_title = array_unique($this->breadcrumbs);
137    }
138
139    /**
140     * @since   1.0.0
141     * @version 1.0.0 Initial version
142     */
143    public function initPageHeaderToolbar()
144    {
145        parent::initPageHeaderToolbar();
146        $this->page_header_toolbar_btn = [];
147    }
148
149    /**
150     * @since   1.0.0
151     * @version 1.0.0 Initial version
152     */
153    public function postProcess()
154    {
155        if (Tools::getValue('action') == 'GetModuleQuickView' && Tools::getValue('ajax') == '1') {
156            $this->ajaxProcessGetModuleQuickView();
157        }
158        if ($this->action) {
159            $this->saveRestrictions($this->action);
160        }
161    }
162
163    /**
164     * @since   1.0.0
165     * @version 1.0.0 Initial version
166     */
167    public function initProcess()
168    {
169        if ($this->tabAccess['edit'] === '1') {
170            if (Tools::isSubmit('submitModulecountry')) {
171                $this->action = 'country';
172            } elseif (Tools::isSubmit('submitModulecurrency')) {
173                $this->action = 'currency';
174            } elseif (Tools::isSubmit('submitModulegroup')) {
175                $this->action = 'group';
176            } elseif (Tools::isSubmit('submitModulereference')) {
177                $this->action = 'carrier';
178            }
179        } else {
180            $this->errors[] = Tools::displayError('You do not have permission to edit this.');
181        }
182    }
183
184    /**
185     * @param $type
186     *
187     * @since   1.0.0
188     * @version 1.0.0 Initial version
189     */
190    protected function saveRestrictions($type)
191    {
192        // Delete type restrictions for active module.
193        $modules = [];
194        foreach ($this->payment_modules as $module) {
195            if ($module->active) {
196                $modules[] = (int) $module->id;
197            }
198        }
199
200        Db::getInstance()->execute('
201			DELETE FROM `'._DB_PREFIX_.'module_'.bqSQL($type).'`
202			WHERE id_shop = '.$this->context->shop->id.'
203			AND `id_module` IN ('.implode(', ', $modules).')'
204        );
205
206        if ($type === 'carrier') {
207            // Fill the new restriction selection for active module.
208            $values = array();
209            foreach ($this->payment_modules as $module) {
210                if ($module->active && isset($_POST[$module->name.'_reference'])) {
211                    foreach ($_POST[$module->name.'_reference'] as $selected) {
212                        $values[] = '('.(int) $module->id.', '.(int) $this->context->shop->id.', '.(int) $selected.')';
213                    }
214                }
215            }
216            if (count($values)) {
217                Db::getInstance()->execute('
218				INSERT INTO `'._DB_PREFIX_.'module_carrier`
219				(`id_module`, `id_shop`, `id_reference`)
220				VALUES '.implode(',', $values));
221            }
222        } else {
223            // Fill the new restriction selection for active module.
224            $values = array();
225            foreach ($this->payment_modules as $module) {
226                if ($module->active && isset($_POST[$module->name.'_'.$type.''])) {
227                    foreach ($_POST[$module->name.'_'.$type.''] as $selected) {
228                        $values[] = '('.(int) $module->id.', '.(int) $this->context->shop->id.', '.(int) $selected.')';
229                    }
230                }
231            }
232            if (count($values)) {
233                Db::getInstance()->execute('
234				INSERT INTO `'._DB_PREFIX_.'module_'.bqSQL($type).'`
235				(`id_module`, `id_shop`, `id_'.bqSQL($type).'`)
236				VALUES '.implode(',', $values));
237            }
238        }
239
240        Tools::redirectAdmin(static::$currentIndex.'&conf=4'.'&token='.$this->token);
241    }
242
243    /**
244     * @since   1.0.0
245     * @version 1.0.0 Initial version
246     */
247    public function initContent()
248    {
249        $this->display = 'view';
250
251        return parent::initContent();
252    }
253
254    /**
255     * @since   1.0.0
256     * @version 1.0.0 Initial version
257     */
258    public function setMedia()
259    {
260        parent::setMedia();
261        $this->addJqueryPlugin('fancybox');
262    }
263
264    /**
265     * @return string
266     *
267     * @since   1.0.0
268     * @version 1.0.0 Initial version
269     */
270    public function renderView()
271    {
272        $this->toolbar_title = $this->l('Payment');
273        unset($this->toolbar_btn['back']);
274
275        $shopContext = (!Shop::isFeatureActive() || Shop::getContext() == Shop::CONTEXT_SHOP);
276        if (!$shopContext) {
277            $this->tpl_view_vars = ['shop_context' => $shopContext];
278
279            return parent::renderView();
280        }
281
282        $displayRestrictions = false;
283        foreach ($this->payment_modules as $module) {
284            if ($module->active) {
285                $displayRestrictions = true;
286                break;
287            }
288        }
289
290        $lists = [
291            [
292                'items'      => Currency::getCurrencies(),
293                'title'      => $this->l('Currency restrictions'),
294                'desc'       => $this->l('Please mark each checkbox for the currency, or currencies, for which you want the payment module(s) to be available.'),
295                'name_id'    => 'currency',
296                'identifier' => 'id_currency',
297                'icon'       => 'icon-money',
298            ],
299            [
300                'items'      => Group::getGroups($this->context->language->id, true),
301                'title'      => $this->l('Group restrictions'),
302                'desc'       => $this->l('Please mark each checkbox for the customer group(s), for which you want the payment module(s) to be available.'),
303                'name_id'    => 'group',
304                'identifier' => 'id_group',
305                'icon'       => 'icon-group',
306            ],
307            [
308                'items'      => Country::getCountries($this->context->language->id),
309                'title'      => $this->l('Country restrictions'),
310                'desc'       => $this->l('Please mark each checkbox for the country, or countries, for which you want the payment module(s) to be available.'),
311                'name_id'    => 'country',
312                'identifier' => 'id_country',
313                'icon'       => 'icon-globe',
314            ],
315            [
316                'items'      => Carrier::getCarriers($this->context->language->id, false, false, false, null, Carrier::ALL_CARRIERS),
317                'title'      => $this->l('Carrier restrictions'),
318                'desc'       => $this->l('Please mark each checkbox for the carrier, or carrier, for which you want the payment module(s) to be available.'),
319                'name_id'    => 'reference',
320                'identifier' => 'id_reference',
321                'icon'       => 'icon-truck',
322            ],
323        ];
324
325        foreach ($lists as $keyList => $list) {
326            $list['check_list'] = [];
327            foreach ($list['items'] as $keyItem => $item) {
328                $nameId = $list['name_id'];
329
330                if ($nameId === 'currency'
331                    && mb_strpos($list['items'][$keyItem]['name'], '('.$list['items'][$keyItem]['iso_code'].')') === false) {
332                    $list['items'][$keyItem]['name'] = sprintf($this->l('%1$s (%2$s)'), $list['items'][$keyItem]['name'], $list['items'][$keyItem]['iso_code']);
333                }
334
335                foreach ($this->payment_modules as $keyModule => $module) {
336                    if (isset($module->$nameId) && in_array($item['id_'.$nameId], $module->$nameId)) {
337                        $list['items'][$keyItem]['check_list'][$keyModule] = 'checked';
338                    } else {
339                        $list['items'][$keyItem]['check_list'][$keyModule] = 'unchecked';
340                    }
341
342                    if (!isset($module->$nameId)) {
343                        $module->$nameId = [];
344                    }
345                    if (!isset($module->currencies_mode)) {
346                        $module->currencies_mode = '';
347                    }
348                    if (!isset($module->currencies)) {
349                        $module->currencies = '';
350                    }
351
352                    // If is a country list and the country is limited, remove it from list
353                    if ($nameId == 'country'
354                        && isset($module->limited_countries)
355                        && !empty($module->limited_countries)
356                        && is_array($module->limited_countries)
357                        && !(in_array(strtoupper($item['iso_code']), array_map('strtoupper', $module->limited_countries)))) {
358                        $list['items'][$keyItem]['check_list'][$keyModule] = null;
359                    }
360                }
361            }
362            // update list
363            $lists[$keyList] = $list;
364        }
365
366        $this->tpl_view_vars = [
367            'modules_list'         => $this->renderModulesList(),
368            'display_restrictions' => $displayRestrictions,
369            'lists'                => $lists,
370            'ps_base_uri'          => __PS_BASE_URI__,
371            'payment_modules'      => $this->payment_modules,
372            'url_submit'           => static::$currentIndex.'&token='.$this->token,
373            'shop_context'         => $shopContext,
374        ];
375
376        return parent::renderView();
377    }
378
379    /**
380     * @return mixed|string
381     *
382     * @since   1.0.0
383     * @version 1.0.0 Initial version
384     */
385    public function renderModulesList()
386    {
387        if ($this->getModulesList($this->filter_modules_list)) {
388            $activeList = [];
389            $unactiveList = [];
390            foreach ($this->modules_list as $key => $module) {
391                if (in_array($module->name, $this->list_partners_modules)) {
392                    $this->modules_list[$key]->type = 'addonsPartner';
393                }
394                if (isset($module->description_full) && trim($module->description_full) != '') {
395                    $module->show_quick_view = true;
396                }
397
398                if ($module->active) {
399                    $activeList[] = $module;
400                } else {
401                    $unactiveList[] = $module;
402                }
403            }
404
405            $helper = new Helper();
406            $fetch = '';
407
408            if (isset($activeList)) {
409                $this->context->smarty->assign('panel_title', $this->l('Active payment'));
410                $fetch = $helper->renderModulesList($activeList);
411            }
412
413            $this->context->smarty->assign(
414                [
415                    'panel_title' => $this->l('Recommended payment gateways'),
416                    'view_all'    => true,
417                ]
418            );
419            $fetch .= $helper->renderModulesList($unactiveList);
420
421            return $fetch;
422        }
423    }
424}
425