Passed
Pull Request — master (#48)
by
unknown
02:31
created

WC_Pagantis_Gateway::getKeysParametersUrl()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 8
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 12
rs 10
1
<?php
2
3
//namespace empty
4
use Pagantis\ModuleUtils\Exception\OrderNotFoundException;
5
use Pagantis\OrdersApiClient\Model\Order\User\Address;
6
use Pagantis\OrdersApiClient\Model\Order\User;
7
use Pagantis\OrdersApiClient\Model\Order\User\OrderHistory;
8
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details;
9
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart;
10
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product;
11
use Pagantis\OrdersApiClient\Model\Order\Metadata;
12
use Pagantis\OrdersApiClient\Model\Order\Configuration\Urls;
13
use Pagantis\OrdersApiClient\Model\Order\Configuration\Channel;
14
use Pagantis\OrdersApiClient\Model\Order\Configuration;
15
use Pagantis\OrdersApiClient\Client;
16
use Pagantis\OrdersApiClient\Model\Order;
17
use Pagantis\ModuleUtils\Model\Log\LogEntry;
18
19
if (! defined('ABSPATH')) {
20
    exit;
21
}
22
23
define('__ROOT__', dirname(dirname(__FILE__)));
24
25
class WC_Pagantis_Gateway extends WC_Payment_Gateway
0 ignored issues
show
Bug introduced by
The type WC_Payment_Gateway 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...
26
{
27
    const METHOD_ID = 'pagantis';
28
29
    /**
30
     * Customizable configuration options
31
     *
32
     * @var array $extraConfig
33
     */
34
    private $extraConfig;
35
36
    /**
37
     * Language to facilitate localization
38
     *
39
     * @var string $language
40
     */
41
    public $language;
42
43
44
    /**
45
     * Array of allowed currencies with Pagantis
46
     *
47
     * @var array $allowed_currencies
48
     */
49
    private $allowed_currencies;
50
51
52
    /**
53
     * WcPagantisGateway constructor.
54
     */
55
    public function __construct()
56
    {
57
        require_once dirname(__FILE__) . '/../includes/class-wc-pagantis-config.php';
58
        require_once dirname(__FILE__) . '/../includes/class-wc-pagantis-logger.php';
59
        require_once dirname(__FILE__) . '/../includes/functions.php';
60
        //Mandatory vars for plugin
61
        $this->id           = PAGANTIS_PLUGIN_ID;
0 ignored issues
show
Bug Best Practice introduced by
The property id does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
62
        $this->has_fields   = true;
0 ignored issues
show
Bug Best Practice introduced by
The property has_fields does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
63
        $this->method_title = ucfirst($this->id);
0 ignored issues
show
Bug Best Practice introduced by
The property method_title does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
64
        //Useful vars
65
        $this->template_path = plugin_dir_path(__FILE__) . '../templates/';
0 ignored issues
show
Bug Best Practice introduced by
The property template_path does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
Bug introduced by
The function plugin_dir_path 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

65
        $this->template_path = /** @scrutinizer ignore-call */ plugin_dir_path(__FILE__) . '../templates/';
Loading history...
66
67
        $this->allowed_currencies = array('EUR');
68
        $this->language           = strstr(get_locale(), '_', true);
0 ignored issues
show
Bug introduced by
The function get_locale 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

68
        $this->language           = strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true);
Loading history...
69
        if ($this->language === '') {
70
            $this->language = 'ES';
71
        }
72
        $this->icon = 'https://cdn.digitalorigin.com/assets/master/logos/pg-130x30.svg';
0 ignored issues
show
Bug Best Practice introduced by
The property icon does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
73
74
        //Panel form fields
75
        $this->init_form_fields();
76
        $this->init_settings();
77
78
        $this->extraConfig = WC_Pagantis_Config::getExtraConfig();
79
        $this->title       = __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
0 ignored issues
show
Bug Best Practice introduced by
The property title does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
Bug introduced by
The function __ 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

79
        $this->title       = /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
Loading history...
80
81
        $this->method_description =
0 ignored issues
show
Bug Best Practice introduced by
The property method_description does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
82
            __('Give the flexibility to your clients to pay in installments with Pagantis!', 'pagantis');
83
        $this->check_deprecated_arguments();
84
        $this->set_payment_urls();
85
        //Hooks
86
        add_action(
0 ignored issues
show
Bug introduced by
The function add_action 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

86
        /** @scrutinizer ignore-call */ 
87
        add_action(
Loading history...
87
            'woocommerce_update_options_payment_gateways_' . $this->id,
88
            array($this, 'process_admin_options')
89
        ); //Save plugin options
90
        add_action(
91
            'admin_notices',
92
            array($this, 'check_plugin_settings')
93
        );                          //Check config fields
94
        add_action(
95
            'woocommerce_receipt_' . $this->id,
96
            array($this, 'get_wc_order_received_page')
97
        );          //Pagantis form
98
        add_action('woocommerce_api_wcpagantisgateway', array($this, 'pagantisNotification'));      //Json Notification
99
        add_filter('woocommerce_payment_complete_order_status', array($this, 'pagantisCompleteStatus'), 10, 3);
0 ignored issues
show
Bug introduced by
The function add_filter 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

99
        /** @scrutinizer ignore-call */ 
100
        add_filter('woocommerce_payment_complete_order_status', array($this, 'pagantisCompleteStatus'), 10, 3);
Loading history...
100
        add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
101
        //add_action('wp_enqueue_scripts', array($this, 'enqueue_ajax_scripts'));
102
    }
103
104
    public function enqueue_ajax_scripts()
105
    {
106
        if ($this->enabled !== 'yes' || ! is_checkout() || is_order_received_page()
0 ignored issues
show
Bug introduced by
The function is_checkout 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

106
        if ($this->enabled !== 'yes' || ! /** @scrutinizer ignore-call */ is_checkout() || is_order_received_page()
Loading history...
Bug introduced by
The function is_order_received_page 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

106
        if ($this->enabled !== 'yes' || ! is_checkout() || /** @scrutinizer ignore-call */ is_order_received_page()
Loading history...
107
            || is_wc_endpoint_url('order-pay')
0 ignored issues
show
Bug introduced by
The function is_wc_endpoint_url 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

107
            || /** @scrutinizer ignore-call */ is_wc_endpoint_url('order-pay')
Loading history...
108
        ) {
109
            return;
110
        }
111
112
        wp_register_script(
0 ignored issues
show
Bug introduced by
The function wp_register_script 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

112
        /** @scrutinizer ignore-call */ 
113
        wp_register_script(
Loading history...
113
            'pagantis-checkout',
114
            plugins_url('../assets/js/pagantis-checkout.js', __FILE__),
0 ignored issues
show
Bug introduced by
The function plugins_url 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

114
            /** @scrutinizer ignore-call */ 
115
            plugins_url('../assets/js/pagantis-checkout.js', __FILE__),
Loading history...
115
            array('jquery', 'woocommerce', 'wc-checkout', 'wc-country-select', 'wc-address-i18n'),
116
            PAGANTIS_VERSION,
117
            true
118
        );
119
        wp_enqueue_script('pagantis-checkout');
0 ignored issues
show
Bug introduced by
The function wp_enqueue_script 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

119
        /** @scrutinizer ignore-call */ 
120
        wp_enqueue_script('pagantis-checkout');
Loading history...
120
121
        $checkout_localize_params                        = array();
122
        $checkout_localize_params['place_order_url']     = WC_AJAX::get_endpoint('pagantis_checkout');
0 ignored issues
show
Bug introduced by
The type WC_AJAX 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...
123
        $checkout_localize_params['place_order_nonce']   = wp_create_nonce('pagantis_checkout');
0 ignored issues
show
Bug introduced by
The function wp_create_nonce 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

123
        $checkout_localize_params['place_order_nonce']   = /** @scrutinizer ignore-call */ wp_create_nonce('pagantis_checkout');
Loading history...
124
        $checkout_localize_params['wc_ajax_url']         = WC_AJAX::get_endpoint('%%endpoint%%');
125
        $checkout_localize_params['i18n_checkout_error'] =
126
            esc_attr__('Error processing pagantis checkout. Please try again.', 'pagantis');
0 ignored issues
show
Bug introduced by
The function esc_attr__ 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

126
            /** @scrutinizer ignore-call */ 
127
            esc_attr__('Error processing pagantis checkout. Please try again.', 'pagantis');
Loading history...
127
128
        wp_localize_script('pagantis-checkout', 'pagantis_params', $checkout_localize_params);
0 ignored issues
show
Bug introduced by
The function wp_localize_script 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

128
        /** @scrutinizer ignore-call */ 
129
        wp_localize_script('pagantis-checkout', 'pagantis_params', $checkout_localize_params);
Loading history...
129
130
        wp_enqueue_script('pagantis_params');
131
    }
132
133
    /**
134
     * @param $mofile
135
     * @param $domain
136
     *
137
     * @return string
138
     */
139
    public function loadPagantisTranslation($mofile, $domain)
140
    {
141
        if ('pagantis' === $domain) {
142
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . get_locale() . '.mo';
0 ignored issues
show
Bug introduced by
The constant WP_LANG_DIR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The function get_locale 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

142
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . /** @scrutinizer ignore-call */ get_locale() . '.mo';
Loading history...
143
        }
144
145
        return $mofile;
146
    }
147
148
    /**
149
     * Initialise Gateway Settings Form Fields.
150
     *
151
     * @see WC_Settings_API
152
     */
153
    public function init_form_fields()
154
    {
155
        $this->form_fields = include(plugin_dir_path(__FILE__) . '../includes/settings-pagantis.php');
0 ignored issues
show
Bug introduced by
The function plugin_dir_path 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

155
        $this->form_fields = include(/** @scrutinizer ignore-call */ plugin_dir_path(__FILE__) . '../includes/settings-pagantis.php');
Loading history...
Bug Best Practice introduced by
The property form_fields does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
156
    }
157
158
    /***********
159
     * HOOKS
160
     ***********/
161
162
    /**
163
     * Check dependencies.
164
     *
165
     * @hook   admin_notices
166
     * @throws Exception
167
     * @todo   https://wordpress.stackexchange.com/questions/242705/how-to-stop-showing-admin-notice-after-close-button-has-been-clicked
168
     */
169
    public function check_plugin_settings()
170
    {
171
        if (! pg_wc_is_screen_correct()) {
172
            return;
173
        }
174
175
        if ($this->settings['enabled'] !== 'yes') {
176
            WC_Admin_Notices::add_custom_notice(
0 ignored issues
show
Bug introduced by
The type WC_Admin_Notices 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...
177
                PAGANTIS_PLUGIN_ID . 'first_setup',
178
                sprintf(// translators: 1:  URL to WP plugin page.
179
                    __(
0 ignored issues
show
Bug introduced by
The function __ 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

179
                    /** @scrutinizer ignore-call */ 
180
                    __(
Loading history...
180
                        'Activate Pagantis to start offering comfortable payments in installments to your clients. <a class="button button-primary" href="%1$s">Activate Pagantis now!</a>',
181
                        'pagantis'
182
                    ),
183
                    pg_wc_get_pagantis_admin_url()
184
                )
185
            );
186
        }
187
        if (WC_Admin_Notices::has_notice(PAGANTIS_PLUGIN_ID . 'first_setup') && $this->settings['enabled'] === 'yes') {
188
            WC_Admin_Notices::remove_notice(PAGANTIS_PLUGIN_ID . 'first_setup');
189
        }
190
191
        if ($this->settings['pagantis_public_key'] === '' xor $this->settings['pagantis_private_key'] === ''
192
                                                              && $this->settings['enabled'] === 'yes'
193
        ) {
194
            WC_Admin_Notices::add_custom_notice(
195
                PAGANTIS_PLUGIN_ID . 'keys_setup',
196
                sprintf(// translators: 1:  URL to WP plugin page.
197
                    __(
198
                        'Set your Pagantis merchant keys to start offering comfortable payments in installments  <a class="button button-primary" href="%1$s">Go to keys setup</a></p>',
199
                        'pagantis'
200
                    ),
201
                    pg_wc_get_pagantis_admin_url()
202
                )
203
            );
204
        }
205
206
        if ($this->settings['pagantis_public_key'] === '' xor $this->settings['pagantis_private_key'] === ''
207
                                                              || $this->settings['enabled'] === 'yes'
208
        ) {
209
            WC_Admin_Notices::add_custom_notice(
210
                PAGANTIS_PLUGIN_ID . 'keys_check',
211
                sprintf(// translators: 1:  URL to WP plugin page.
212
                    __(
213
                        'Set your Pagantis merchant Api keys to start offering comfortable payments in installments.  <a class="button button-primary" href="%1$s">Go to keys setup</a>',
214
                        'pagantis'
215
                    ),
216
                    pg_wc_get_pagantis_admin_url()
217
                )
218
            );
219
        }
220
221
        if ($this->settings['pagantis_public_key'] !== '' && $this->settings['pagantis_private_key'] !== ''
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: ($this->settings['pagant...ngs['enabled'] === 'no', Probably Intended Meaning: $this->settings['paganti...gs['enabled'] === 'no')
Loading history...
222
                                                              || $this->settings['enabled'] === 'no'
223
        ) {
224
            WC_Admin_Notices::add_custom_notice(
225
                PAGANTIS_PLUGIN_ID . 'finish_setup',
226
                sprintf(// translators: 1:  URL to WP plugin page.
227
                    __(
228
                        'It seems that your merchant keys are setup but the plugin is not active Activate the Pagantis plugin to start offering comfortable payments in installments to your clients.  <a class="button button-primary" href="%1$s">Go to Pagantis settings</a>',
229
                        'pagantis'
230
                    ),
231
                    pg_wc_get_pagantis_admin_url()
232
                )
233
            );
234
        }
235
        if (WC_Admin_Notices::has_notice(PAGANTIS_PLUGIN_ID . 'keys_check'
236
                                             && $this->settings['pagantis_public_key'] !== ''
237
                                             && $this->settings['pagantis_private_key'] !== ''
238
        && $this->settings['enabled'] === 'yes')
239
        ) {
240
            WC_Admin_Notices::remove_notice(PAGANTIS_PLUGIN_ID . 'keys_setup');
241
        }
242
243
244
        if (WC_Admin_Notices::has_notice(PAGANTIS_PLUGIN_ID . 'first_setup'
245
                                         && $this->settings['pagantis_public_key'] === ''
246
        && $this->settings['pagantis_private_key'] === '')
247
        ) {
248
            WC_Admin_Notices::remove_notice(PAGANTIS_PLUGIN_ID . 'keys_setup');
249
        }
250
251
252
        if (WC_Admin_Notices::has_notice(PAGANTIS_PLUGIN_ID . 'keys_check') xor WC_Admin_Notices::has_notice(PAGANTIS_PLUGIN_ID . 'first_setup')
253
            && $this->settings['pagantis_public_key'] !== ''
254
            || $this->settings['pagantis_private_key'] !== ''
255
        ) {
256
            WC_Admin_Notices::remove_notice(PAGANTIS_PLUGIN_ID . 'first_setup');
257
            WC_Admin_Notices::remove_notice(PAGANTIS_PLUGIN_ID . 'keys_check');
258
        }
259
260
        if (! in_array(get_woocommerce_currency(), $this->allowed_currencies, true)) {
0 ignored issues
show
Bug introduced by
The function get_woocommerce_currency 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

260
        if (! in_array(/** @scrutinizer ignore-call */ get_woocommerce_currency(), $this->allowed_currencies, true)) {
Loading history...
261
            WC_Admin_Settings::add_error(__('Error: Pagantis only can be used in Euros.', 'pagantis'));
0 ignored issues
show
Bug introduced by
The type WC_Admin_Settings 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
            $this->settings['enabled'] = 'no';
0 ignored issues
show
Bug Best Practice introduced by
The property settings does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
263
        }
264
265
        if ($this->extraConfig['PAGANTIS_SIMULATOR_MAX_INSTALLMENTS'] < '2'
266
            || $this->extraConfig['PAGANTIS_SIMULATOR_MAX_INSTALLMENTS'] > '12'
267
        ) {
268
            $this->settings['enabled'] = 'no';
269
270
            WC_Admin_Settings::add_error(__(
271
                'Error: Pagantis can be used up to 12 installments please contact your account manager',
272
                'pagantis'
273
            ));
274
        }
275
276
        if ($this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS'] < '2'
277
            || $this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS'] > '12'
278
        ) {
279
            WC_Admin_Settings::add_error(__(
280
                'Error: Pagantis can be used from 2 installments please contact your account manager',
281
                'pagantis'
282
            ));
283
        }
284
        if ($this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'] < 0) {
285
            WC_Admin_Settings::add_error(__('Error: Pagantis can not be used for free products', 'pagantis'));
286
        }
287
    }
288
289
    /**
290
     * PANEL - Display admin setting panel
291
     *
292
     * @hook woocommerce_update_options_payment_gateways_pagantis
293
     */
294
    public function admin_options()
295
    {
296
        $template_fields = array(
297
            'panel_description' => $this->method_description,
298
            'button1_label'     => __('Login to your panel', 'pagantis'),
0 ignored issues
show
Bug introduced by
The function __ 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

298
            'button1_label'     => /** @scrutinizer ignore-call */ __('Login to your panel', 'pagantis'),
Loading history...
299
            'button2_label'     => __('Documentation', 'pagantis'),
300
            'logo'              => $this->icon,
301
            'settings'          => $this->generate_settings_html($this->form_fields, false),
302
        );
303
        wc_get_template('admin_header.php', $template_fields, '', $this->template_path);
0 ignored issues
show
Bug introduced by
The function wc_get_template 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

303
        /** @scrutinizer ignore-call */ 
304
        wc_get_template('admin_header.php', $template_fields, '', $this->template_path);
Loading history...
304
    }
305
306
307
    /**
308
     * PANEL - Check admin panel fields -> Hook: admin_notices
309
     *
310
     * @deprecated since 8.3.7
311
     */
312
    public function pagantisCheckFields()
313
    {
314
        _deprecated_function(__METHOD__, '8.3.7', 'check_dependencies');
0 ignored issues
show
Bug introduced by
The function _deprecated_function 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

314
        /** @scrutinizer ignore-call */ 
315
        _deprecated_function(__METHOD__, '8.3.7', 'check_dependencies');
Loading history...
315
    }
316
317
    private function check_deprecated_arguments()
318
    {
319
        _deprecated_argument(
0 ignored issues
show
Bug introduced by
The function _deprecated_argument 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

319
        /** @scrutinizer ignore-call */ 
320
        _deprecated_argument(
Loading history...
320
            $this->mainFileLocation,
321
            '8.3.7',
322
            '$this->mainFileLocation has been deprecated please use PAGANTIS_VERSION'
323
        );
324
        _deprecated_argument(
325
            $this->plugin_info,
326
            '8.3.7',
327
            ' $this->plugin_info has been deprecated please use PAGANTIS_VERSION'
328
        );
329
        _deprecated_argument(
330
            PAGANTIS_PLUGIN_ID,
331
            '8.3.7',
332
            ' METHOD_ID has been deprecated please use PAGANTIS_PLUGIN_ID'
333
        );
334
    }
335
336
    /**
337
     * CHECKOUT - Generate the pagantis form. "Return" iframe or redirect. - Hook: woocommerce_receipt_pagantis
338
     *
339
     * @param $order_id
340
     *
341
     * @hook woocommerce_receipt_pagantis
342
     * @throws Exception
343
     */
344
    public function get_wc_order_received_page($order_id)
345
    {
346
        try {
347
            require_once(__ROOT__ . '/vendor/autoload.php');
348
            global $woocommerce;
349
            $order = wc_get_order($order_id);
0 ignored issues
show
Bug introduced by
The function wc_get_order 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

349
            $order = /** @scrutinizer ignore-call */ wc_get_order($order_id);
Loading history...
350
            $order->set_payment_method(ucfirst($this->id));
351
            $order->save();
352
353
            if (! isset($order)) {
354
                throw new Exception(__('Order not found', 'pagantis'));
0 ignored issues
show
Bug introduced by
The function __ 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

354
                throw new Exception(/** @scrutinizer ignore-call */ __('Order not found', 'pagantis'));
Loading history...
355
            }
356
357
            $shippingAddress = $order->get_address('shipping');
358
            $billingAddress  = $order->get_address('billing');
359
            if ($shippingAddress['address_1'] === '') {
360
                $shippingAddress = $billingAddress;
361
            }
362
363
            $national_id = $this->getNationalId($order);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $national_id is correct as $this->getNationalId($order) targeting WC_Pagantis_Gateway::getNationalId() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
364
            $tax_id      = $this->getTaxId($order);
365
366
            $userAddress = new Address();
367
            $userAddress->setZipCode($shippingAddress['postcode'])->setFullName($shippingAddress['first_name'] . ' '
368
            . $shippingAddress['last_name'])
369
                        ->setCountryCode($shippingAddress['country'] !== '' ? strtoupper($shippingAddress['country'])
370
                        : strtoupper($this->language))->setCity($shippingAddress['city'])
371
                        ->setAddress($shippingAddress['address_1'] . ' ' . $shippingAddress['address_2']);
372
            $orderShippingAddress = new Address();
373
            $orderShippingAddress->setZipCode($shippingAddress['postcode'])->setFullName($shippingAddress['first_name']
374
                                                                                         . ' '
375
            . $shippingAddress['last_name'])
376
                                ->setCountryCode($shippingAddress['country'] !== ''
377
                                ? strtoupper($shippingAddress['country']) : strtoupper($this->language))
378
                                ->setCity($shippingAddress['city'])->setAddress($shippingAddress['address_1'] . ' '
379
                                . $shippingAddress['address_2'])
380
                                 ->setFixPhone($shippingAddress['phone'])->setMobilePhone($shippingAddress['phone'])
381
                                 ->setNationalId($national_id)->setTaxId($tax_id);
382
            $orderBillingAddress = new Address();
383
            $orderBillingAddress->setZipCode($billingAddress['postcode'])->setFullName($billingAddress['first_name']
384
                                                                                       . ' '
385
            . $billingAddress['last_name'])
386
                                ->setCountryCode($billingAddress['country'] !== ''
387
                                ? strtoupper($billingAddress['country']) : strtoupper($this->language))
388
                                ->setCity($billingAddress['city'])->setAddress($billingAddress['address_1'] . ' '
389
                                . $billingAddress['address_2'])
390
                                ->setFixPhone($billingAddress['phone'])->setMobilePhone($billingAddress['phone'])
391
                                ->setNationalId($national_id)->setTaxId($tax_id);
392
            $orderUser = new User();
393
            $orderUser->setAddress($userAddress)->setFullName($billingAddress['first_name'] . ' '
394
            . $billingAddress['last_name'])
395
                      ->setBillingAddress($orderBillingAddress)->setEmail($billingAddress['email'])
396
                      ->setFixPhone($billingAddress['phone'])->setMobilePhone($billingAddress['phone'])
397
                      ->setShippingAddress($orderShippingAddress)->setNationalId($national_id)->setTaxId($tax_id);
398
399
            $previousOrders = $this->getOrders($order->get_user(), $billingAddress['email']);
400
            foreach ($previousOrders as $previousOrder) {
401
                $orderHistory = new OrderHistory();
402
                $orderElement = wc_get_order($previousOrder);
403
                $orderCreated = $orderElement->get_date_created();
404
                $orderHistory->setAmount(intval(100 * $orderElement->get_total()))
405
                             ->setDate(new \DateTime($orderCreated->date('Y-m-d H:i:s')));
0 ignored issues
show
Bug introduced by
new DateTime($orderCreated->date('Y-m-d H:i:s')) of type DateTime is incompatible with the type string expected by parameter $date of Pagantis\OrdersApiClient...OrderHistory::setDate(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

405
                             ->setDate(/** @scrutinizer ignore-type */ new \DateTime($orderCreated->date('Y-m-d H:i:s')));
Loading history...
406
                $orderUser->addOrderHistory($orderHistory);
407
            }
408
409
            $metadataOrder = new Metadata();
410
            $metadata      = array(
411
                'pg_module'  => 'woocommerce',
412
                'pg_version' => PAGANTIS_VERSION,
413
                'ec_module'  => 'woocommerce',
414
                'ec_version' => WC()->version,
0 ignored issues
show
Bug introduced by
The function WC 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

414
                'ec_version' => /** @scrutinizer ignore-call */ WC()->version,
Loading history...
415
            );
416
417
            foreach ($metadata as $key => $metadatum) {
418
                $metadataOrder->addMetadata($key, $metadatum);
419
            }
420
421
            $details      = new Details();
422
            $shippingCost = $order->shipping_total;
423
            $details->setShippingCost(intval(strval(100 * $shippingCost)));
424
            $items          = $order->get_items();
425
            $promotedAmount = 0;
426
            foreach ($items as $key => $item) {
427
                $wcProduct          = $item->get_product();
428
                $product            = new Product();
429
                $productDescription = sprintf(
430
                    '%s %s %s',
431
                    $wcProduct->get_name(),
432
                    $wcProduct->get_description(),
433
                    $wcProduct->get_short_description()
434
                );
435
                $productDescription = substr($productDescription, 0, 9999);
436
437
                $product->setAmount(intval(100 * ($item->get_total() + $item->get_total_tax())))
438
                        ->setQuantity($item->get_quantity())->setDescription($productDescription);
439
                $details->addProduct($product);
440
441
                $promotedProduct = $this->isPromoted($item->get_product_id());
442
                if ($promotedProduct === 'true') {
443
                    $promotedAmount += $product->getAmount();
444
                    $promotedMessage =
445
                        'Promoted Item: ' . $wcProduct->get_name() . ' - Price: ' . $item->get_total() . ' - Qty: '
446
                        . $product->getQuantity() . ' - Item ID: ' . $item['id_product'];
447
                    $promotedMessage = substr($promotedMessage, 0, 999);
448
                    $metadataOrder->addMetadata('promotedProduct', $promotedMessage);
449
                }
450
            }
451
452
            $orderShoppingCart = new ShoppingCart();
453
            $orderShoppingCart->setDetails($details)->setOrderReference($order->get_id())
454
                              ->setPromotedAmount($promotedAmount)->setTotalAmount(intval(strval(100 * $order->total)));
455
            $orderConfigurationUrls = new Urls();
456
            $cancelUrl              = $this->getKoUrl($order);
457
            $callback_arg           = array(
458
                'wc-api'         => 'wcpagantisgateway',
459
                'key'            => $order->get_order_key(),
460
                'order-received' => $order->get_id(),
461
                'origin'         => '',
462
            );
463
464
            $callback_arg_user           = $callback_arg;
465
            $callback_arg_user['origin'] = 'redirect';
466
            $callback_url_user           = add_query_arg($callback_arg_user, home_url('/'));
0 ignored issues
show
Bug introduced by
The function add_query_arg 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

466
            $callback_url_user           = /** @scrutinizer ignore-call */ add_query_arg($callback_arg_user, home_url('/'));
Loading history...
Bug introduced by
The function home_url 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

466
            $callback_url_user           = add_query_arg($callback_arg_user, /** @scrutinizer ignore-call */ home_url('/'));
Loading history...
467
468
            $callback_arg_notif           = $callback_arg;
469
            $callback_arg_notif['origin'] = 'notification';
470
            $callback_url_notif           = add_query_arg($callback_arg_notif, home_url('/'));
471
472
            $orderConfigurationUrls->setCancel($cancelUrl)->setKo($callback_url_user)
473
                                   ->setAuthorizedNotificationCallback($callback_url_notif)
474
                                   ->setRejectedNotificationCallback(null)->setOk($callback_url_user);
475
            $orderChannel = new Channel();
476
            $orderChannel->setAssistedSale(false)->setType(Channel::ONLINE);
477
478
            $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
479
            $purchaseCountry  = in_array(strtolower($this->language), $allowedCountries, true)
480
                ? $this->language
481
                : in_array(strtolower($shippingAddress['country']), $allowedCountries, true)
482
                    ? $shippingAddress['country'] : in_array(
483
                        strtolower($billingAddress['country']),
484
                        $allowedCountries,
485
                        true
486
                    ) ? $billingAddress['country'] : null;
487
488
            $orderConfiguration = new Configuration();
489
            $orderConfiguration->setChannel($orderChannel)->setUrls($orderConfigurationUrls)
490
                               ->setPurchaseCountry($purchaseCountry);
491
492
            $orderApiClient = new Order();
493
            $orderApiClient->setConfiguration($orderConfiguration)->setMetadata($metadataOrder)
494
                           ->setShoppingCart($orderShoppingCart)->setUser($orderUser);
495
496
            if ($this->pagantis_public_key === '' || $this->pagantis_private_key === '') {
497
                throw new \Exception('Public and Secret Key not found');
498
            }
499
            $orderClient   = new Client($this->pagantis_public_key, $this->pagantis_private_key);
500
            $pagantisOrder = $orderClient->createOrder($orderApiClient);
501
            if ($pagantisOrder instanceof \Pagantis\OrdersApiClient\Model\Order) {
0 ignored issues
show
introduced by
$pagantisOrder is always a sub-type of Pagantis\OrdersApiClient\Model\Order.
Loading history...
502
                $url = $pagantisOrder->getActionUrls()->getForm();
503
                $this->insert_row_in_wc_orders_table($order->get_id(), $pagantisOrder->getId());
504
            } else {
505
                throw new OrderNotFoundException();
506
            }
507
508
            if ($url === '') {
509
                throw new Exception(__('No ha sido posible obtener una respuesta de Pagantis', 'pagantis'));
510
            } elseif ($this->extraConfig['PAGANTIS_FORM_DISPLAY_TYPE'] === '0') {
511
                wp_redirect($url);
0 ignored issues
show
Bug introduced by
The function wp_redirect 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

511
                /** @scrutinizer ignore-call */ 
512
                wp_redirect($url);
Loading history...
512
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
513
            } else {
514
                $template_fields = array(
515
                    'url'         => $url,
516
                    'checkoutUrl' => $cancelUrl,
517
                );
518
                wc_get_template('iframe.php', $template_fields, '', $this->template_path);
0 ignored issues
show
Bug introduced by
The function wc_get_template 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

518
                /** @scrutinizer ignore-call */ 
519
                wc_get_template('iframe.php', $template_fields, '', $this->template_path);
Loading history...
519
            }
520
        } catch (\Exception $exception) {
521
            wc_add_notice(__('Payment error ', 'pagantis') . $exception->getMessage(), 'error');
0 ignored issues
show
Bug introduced by
The function wc_add_notice 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

521
            /** @scrutinizer ignore-call */ 
522
            wc_add_notice(__('Payment error ', 'pagantis') . $exception->getMessage(), 'error');
Loading history...
522
            WC_Pagantis_Logger::insert_log_entry_in_wpdb($exception);
523
            $checkout_url = get_permalink(wc_get_page_id('checkout'));
0 ignored issues
show
Bug introduced by
The function get_permalink 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

523
            $checkout_url = /** @scrutinizer ignore-call */ get_permalink(wc_get_page_id('checkout'));
Loading history...
Bug introduced by
The function wc_get_page_id 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

523
            $checkout_url = get_permalink(/** @scrutinizer ignore-call */ wc_get_page_id('checkout'));
Loading history...
524
            wp_redirect($checkout_url);
525
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
526
        }
527
    }
528
529
    /**
530
     * NOTIFICATION - Endpoint for Json notification - Hook: woocommerce_api_wcpagantisgateway
531
     */
532
    public function pagantisNotification()
533
    {
534
        try {
535
            $origin = ($_SERVER['REQUEST_METHOD'] === 'POST') ? 'Notify' : 'Order';
536
537
            include_once('class-pg-notification-handler.php');
538
            $notify = new WC_PG_Notification_Handler();
539
540
            $notify->setOrigin($origin);
541
            /**
542
             * @var \Pagantis\ModuleUtils\Model\Response\AbstractJsonResponse $result
543
             */
544
            $result = $notify->processInformation();
545
        } catch (Exception $exception) {
546
            $result['notification_message'] = $exception->getMessage();
547
            $result['notification_error']   = true;
548
        }
549
550
        $paymentOrder = wc_get_order($result->getMerchantOrderId());
0 ignored issues
show
Bug introduced by
The function wc_get_order 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

550
        $paymentOrder = /** @scrutinizer ignore-call */ wc_get_order($result->getMerchantOrderId());
Loading history...
551
        if ($paymentOrder instanceof WC_Order) {
0 ignored issues
show
Bug introduced by
The type WC_Order 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...
552
            $orderStatus = strtolower($paymentOrder->get_status());
553
        } else {
554
            $orderStatus = 'cancelled';
555
        }
556
        $acceptedStatus = array('processing', 'completed');
557
        if (in_array($orderStatus, $acceptedStatus, true)) {
558
            $returnUrl = $this->getOkUrl($paymentOrder);
559
        } else {
560
            $returnUrl = $this->getKoUrl($paymentOrder);
561
        }
562
563
        wp_redirect($returnUrl);
0 ignored issues
show
Bug introduced by
The function wp_redirect 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

563
        /** @scrutinizer ignore-call */ 
564
        wp_redirect($returnUrl);
Loading history...
564
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
565
    }
566
567
    /**
568
     * After failed status, set to processing not complete -> Hook: woocommerce_payment_complete_order_status
569
     *
570
     * @param $status
571
     * @param $order_id
572
     * @param $order
573
     *
574
     * @return string
575
     */
576
    public function pagantisCompleteStatus($status, $order_id, $order)
577
    {
578
        if ($order->get_payment_method() === PAGANTIS_PLUGIN_ID) {
579
            if ($order->get_status() === 'failed') {
580
                $status = 'processing';
581
            } elseif ($order->get_status() === 'pending' && $status === 'completed') {
582
                $status = 'processing';
583
            }
584
        }
585
586
        return $status;
587
    }
588
589
    /***********
590
     * REDEFINED FUNCTIONS
591
     ***********/
592
593
    /**
594
     * CHECKOUT - Check if payment method is available (called by woocommerce, can't apply camel caps)
595
     *
596
     * @return bool
597
     */
598
    public function is_available()
599
    {
600
        $locale           = strtolower(strstr(get_locale(), '_', true));
0 ignored issues
show
Bug introduced by
The function get_locale 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

600
        $locale           = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
601
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
602
        $allowedCountry   = (in_array(strtolower($locale), $allowedCountries, true));
603
        $minAmount        = $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'];
604
        $maxAmount        = $this->extraConfig['PAGANTIS_DISPLAY_MAX_AMOUNT'];
605
        $totalPrice       = (int) $this->get_order_total();
606
        $validAmount      = ($totalPrice >= $minAmount && ($totalPrice <= $maxAmount || $maxAmount === '0'));
607
        if ($this->enabled === 'yes' && $this->pagantis_public_key !== '' && $this->pagantis_private_key !== ''
608
            && $validAmount
609
            && $allowedCountry
610
        ) {
611
            return true;
612
        }
613
614
        return false;
615
    }
616
617
    /**
618
     * CHECKOUT - Checkout + admin panel title(method_title - get_title) (called by woocommerce,can't apply camel caps)
619
     *
620
     * @return string
621
     */
622
    public function get_title()
623
    {
624
        return __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
0 ignored issues
show
Bug introduced by
The function __ 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

624
        return /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
Loading history...
625
    }
626
627
    /**
628
     * CHECKOUT - Called after push pagantis button on checkout(called by woocommerce, can't apply camel caps
629
     *
630
     * @param $order_id
631
     *
632
     * @return array
633
     */
634
    public function process_payment($order_id)
635
    {
636
        try {
637
            $order = new WC_Order($order_id);
638
639
            $redirectUrl = $order->get_checkout_payment_url(true); //pagantisReceiptPage function
640
            if (strpos($redirectUrl, 'order-pay=') === false) {
641
                $redirectUrl .= '&order-pay=' . $order_id;
642
            }
643
644
            return array(
645
                'result'   => 'success',
646
                'redirect' => $redirectUrl,
647
            );
648
        } catch (Exception $e) {
649
            wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
0 ignored issues
show
Bug introduced by
The function wc_add_notice 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

649
            /** @scrutinizer ignore-call */ 
650
            wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
Bug introduced by
The function __ 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

649
            wc_add_notice(/** @scrutinizer ignore-call */ __('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
650
651
            return array();
652
        }
653
    }
654
655
    /**
656
     * CHECKOUT - simulator (called by woocommerce, can't apply camel caps)
657
     */
658
    public function payment_fields()
659
    {
660
        $locale           = strtolower(strstr(get_locale(), '_', true));
0 ignored issues
show
Bug introduced by
The function get_locale 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

660
        $locale           = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
661
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
662
        $allowedCountry   = (in_array(strtolower($locale), $allowedCountries, true));
663
        $promotedAmount   = $this->getPromotedAmount();
664
665
        $template_fields = array(
666
            'public_key'            => $this->pagantis_public_key,
667
            'total'                 => WC()->cart->get_total(),
0 ignored issues
show
Bug introduced by
The function WC 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

667
            'total'                 => /** @scrutinizer ignore-call */ WC()->cart->get_total(),
Loading history...
668
            'enabled'               => $this->settings['enabled'],
669
            'min_installments'      => $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'],
670
            'max_installments'      => $this->extraConfig['PAGANTIS_DISPLAY_MAX_AMOUNT'],
671
            'simulator_enabled'     => $this->settings['simulator'],
672
            'locale'                => $locale,
673
            'country'               => $locale,
674
            'allowed_country'       => $allowedCountry,
675
            'simulator_type'        => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE_CHECKOUT'],
676
            'promoted_amount'       => $promotedAmount,
677
            'thousandSeparator'     => $this->extraConfig['PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'],
678
            'decimalSeparator'      => $this->extraConfig['PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR'],
679
            'pagantisSimulatorSkin' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_SKIN'],
680
        );
681
        try {
682
            wc_get_template('checkout_description.php', $template_fields, '', $this->template_path);
0 ignored issues
show
Bug introduced by
The function wc_get_template 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

682
            /** @scrutinizer ignore-call */ 
683
            wc_get_template('checkout_description.php', $template_fields, '', $this->template_path);
Loading history...
683
        } catch (Exception $exception) {
684
            $exception->getMessage();
685
        }
686
    }
687
688
689
    /***********
690
     * UTILS FUNCTIONS
691
     ***********/
692
693
    /**
694
     * set payment module callback urls
695
     */
696
    private function set_payment_urls()
697
    {
698
        $this->settings['ok_url'] =
0 ignored issues
show
Bug Best Practice introduced by
The property settings does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
699
            ($this->extraConfig['PAGANTIS_URL_OK'] !== '') ? $this->extraConfig['PAGANTIS_URL_OK']
700
                : $this->generateOkUrl();
701
        $this->settings['ko_url'] =
702
            ($this->extraConfig['PAGANTIS_URL_KO'] !== '') ? $this->extraConfig['PAGANTIS_URL_KO']
703
                : $this->generateKoUrl();
704
        foreach ($this->settings as $setting_key => $setting_value) {
705
            $this->$setting_key = $setting_value;
706
        }
707
    }
708
709
    /**
710
     * PANEL KO_URL FIELD
711
     * CHECKOUT PAGE => ?page_id=91 // ORDER-CONFIRMATION PAGE => ?page_id=91&order-pay=<order_id>&key=<order_key>
712
     */
713
    private function generateOkUrl()
714
    {
715
        return $this->generateUrl($this->get_return_url());
716
    }
717
718
    /**
719
     * PANEL OK_URL FIELD
720
     */
721
    private function generateKoUrl()
722
    {
723
        return $this->generateUrl(get_permalink(wc_get_page_id('checkout')));
0 ignored issues
show
Bug introduced by
The function get_permalink 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

723
        return $this->generateUrl(/** @scrutinizer ignore-call */ get_permalink(wc_get_page_id('checkout')));
Loading history...
Bug introduced by
The function wc_get_page_id 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

723
        return $this->generateUrl(get_permalink(/** @scrutinizer ignore-call */ wc_get_page_id('checkout')));
Loading history...
724
    }
725
726
    /**
727
     * Replace empty space by {{var}}
728
     *
729
     * @param $url
730
     *
731
     * @return string
732
     */
733
    private function generateUrl($url)
734
    {
735
        $parsed_url = parse_url($url);
736
        if ($parsed_url !== false) {
737
            $parsed_url['query'] = ! isset($parsed_url['query']) ? '' : $parsed_url['query'];
738
            parse_str($parsed_url['query'], $arrayParams);
739
            foreach ($arrayParams as $keyParam => $valueParam) {
740
                if ($valueParam === '') {
741
                    $arrayParams[$keyParam] = '{{' . $keyParam . '}}';
742
                }
743
            }
744
            $parsed_url['query'] = http_build_query($arrayParams);
745
            $return_url          = $this->get_unparsed_url($parsed_url);
746
747
            return urldecode($return_url);
748
        } else {
749
            return $url;
750
        }
751
    }
752
753
    /**
754
     * Replace {{}} by vars values inside ok_url
755
     *
756
     * @param $order
757
     *
758
     * @return string
759
     */
760
    private function getOkUrl($order)
761
    {
762
        return $this->getKeysUrl($order, $this->ok_url);
763
    }
764
765
    /**
766
     * Replace {{}} by vars values inside ko_url
767
     *
768
     * @param $order
769
     *
770
     * @return string
771
     */
772
    private function getKoUrl($order)
773
    {
774
        return $this->getKeysUrl($order, $this->ko_url);
775
    }
776
777
    /**
778
     * Replace {{}} by vars values
779
     *
780
     * @param $order
781
     * @param $url
782
     *
783
     * @return string
784
     */
785
    private function getKeysUrl($order, $url)
786
    {
787
        $defaultFields = (get_class($order) === 'WC_Order') ? array(
788
            'order-received' => $order->get_id(),
789
            'key'            => $order->get_order_key()
790
        ) : array();
791
792
        $parsedUrl = parse_url($url);
793
        if ($parsedUrl !== false) {
794
            //Replace parameters from url
795
            $parsedUrl['query'] = $this->getKeysParametersUrl($parsedUrl['query'], $defaultFields);
796
797
            //Replace path from url
798
            $parsedUrl['path'] = $this->getKeysPathUrl($parsedUrl['path'], $defaultFields);
799
800
            $returnUrl = $this->get_unparsed_url($parsedUrl);
801
802
            return $returnUrl;
803
        }
804
805
        return $url;
806
    }
807
808
    /**
809
     * Replace {{}} by vars values inside parameters
810
     *
811
     * @param $queryString
812
     * @param $defaultFields
813
     *
814
     * @return string
815
     */
816
    private function getKeysParametersUrl($queryString, $defaultFields)
817
    {
818
        parse_str(html_entity_decode($queryString), $arrayParams);
819
        var_export($queryString);
820
        $commonKeys = array_intersect_key($arrayParams, $defaultFields);
821
        if (count($commonKeys)) {
822
            $arrayResult = array_merge($arrayParams, $defaultFields);
823
        } else {
824
            $arrayResult = $arrayParams;
825
        }
826
827
        return urldecode(http_build_query($arrayResult));
828
    }
829
830
    /**
831
     * Replace {{}} by vars values inside path
832
     *
833
     * @param $pathString
834
     * @param $defaultFields
835
     *
836
     * @return string
837
     */
838
    private function getKeysPathUrl($pathString, $defaultFields)
839
    {
840
        $arrayParams = explode('/', $pathString);
841
        foreach ($arrayParams as $keyParam => $valueParam) {
842
            preg_match('#\{{.*?}\}#', $valueParam, $match);
843
            if (count($match)) {
844
                $key                    = str_replace(array('{{', '}}'), array('', ''), $match[0]);
845
                $arrayParams[$keyParam] = $defaultFields[$key];
846
            }
847
        }
848
849
        return implode('/', $arrayParams);
850
    }
851
852
    /**
853
     * Replace {{var}} by empty space
854
     *
855
     * @param $parsed_url
856
     *
857
     * @return string
858
     */
859
    private function get_unparsed_url($parsed_url)
860
    {
861
        $scheme   = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
862
        $host     = isset($parsed_url['host']) ? $parsed_url['host'] : '';
863
        $port     = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
864
        $query    = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
865
        $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
866
        $path     = $parsed_url['path'];
867
868
        return $scheme . $host . $port . $path . $query . $fragment;
869
    }
870
871
    /**
872
     * Get the orders of a customer
873
     *
874
     * @param $current_user
875
     * @param $billingEmail
876
     *
877
     * @return mixed
878
     */
879
    private function getOrders($current_user, $billingEmail)
880
    {
881
        $sign_up         = '';
882
        $total_orders    = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $total_orders is dead and can be removed.
Loading history...
883
        $total_amt       = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $total_amt is dead and can be removed.
Loading history...
884
        $refund_amt      = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $refund_amt is dead and can be removed.
Loading history...
885
        $total_refunds   = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $total_refunds is dead and can be removed.
Loading history...
886
        $partial_refunds = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $partial_refunds is dead and can be removed.
Loading history...
887
        if ($current_user->user_login) {
888
            $is_guest        = 'false';
0 ignored issues
show
Unused Code introduced by
The assignment to $is_guest is dead and can be removed.
Loading history...
889
            $sign_up         = substr($current_user->user_registered, 0, 10);
0 ignored issues
show
Unused Code introduced by
The assignment to $sign_up is dead and can be removed.
Loading history...
890
            $customer_orders = get_posts(array(
0 ignored issues
show
Bug introduced by
The function get_posts 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

890
            $customer_orders = /** @scrutinizer ignore-call */ get_posts(array(
Loading history...
891
                'numberposts' => -1,
892
                'meta_key'    => '_customer_user',
893
                'meta_value'  => $current_user->ID,
894
                'post_type'   => array('shop_order'),
895
                'post_status' => array('wc-completed', 'wc-processing', 'wc-refunded'),
896
            ));
897
        } else {
898
            $is_guest        = 'true';
899
            $customer_orders = get_posts(array(
900
                'numberposts' => -1,
901
                'meta_key'    => '_billing_email',
902
                'meta_value'  => $billingEmail,
903
                'post_type'   => array('shop_order'),
904
                'post_status' => array('wc-completed', 'wc-processing', 'wc-refunded'),
905
            ));
906
            foreach ($customer_orders as $customer_order) {
907
                if (trim($sign_up) === ''
908
                    || strtotime(substr($customer_order->post_date, 0, 10)) <= strtotime($sign_up)
909
                ) {
910
                    $sign_up = substr($customer_order->post_date, 0, 10);
911
                }
912
            }
913
        }
914
915
        return $customer_orders;
916
    }
917
918
919
    /**
920
     *
921
     * @param       $wc_order_id
922
     * @param       $pg_order_id
923
     *
924
     * @throws Exception
925
     * @global wpdb $wpdb WordPress database abstraction object.
926
     */
927
    private function insert_row_in_wc_orders_table($wc_order_id, $pg_order_id)
928
    {
929
        global $wpdb;
930
        $this->check_if_wc_orders_db_table_exist();
931
        $tableName = $wpdb->prefix . PAGANTIS_WC_ORDERS_TABLE;
932
933
        //Check if id exists
934
        $resultsSelect = $wpdb->get_results("SELECT * FROM $tableName WHERE id='$wc_order_id'");
935
        $countResults  = count($resultsSelect);
936
        if ($countResults === 0) {
937
            $wpdb->insert($tableName, array('id' => $wc_order_id, 'order_id' => $pg_order_id), array('%d', '%s'));
938
        } else {
939
            $wpdb->update(
940
                $tableName,
941
                array('order_id' => $pg_order_id),
942
                array('id' => $wc_order_id),
943
                array('%s'),
944
                array('%d')
945
            );
946
        }
947
    }
948
949
    /**
950
     * Check if orders table exists
951
     *
952
     * @global wpdb $wpdb WordPress database abstraction object.
953
     */
954
    private function check_if_wc_orders_db_table_exist()
955
    {
956
        global $wpdb;
957
        $tableName = $wpdb->prefix . PAGANTIS_WC_ORDERS_TABLE;
958
959
        if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") !== $tableName) {
960
            $charset_collate = $wpdb->get_charset_collate();
961
            $sql             = "CREATE TABLE $tableName ( id int, order_id varchar(50), wc_order_id varchar(50),  
962
                  UNIQUE KEY id (id)) $charset_collate";
963
964
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
0 ignored issues
show
Bug introduced by
The constant ABSPATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
965
            dbDelta($sql);
0 ignored issues
show
Bug introduced by
The function dbDelta 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

965
            /** @scrutinizer ignore-call */ 
966
            dbDelta($sql);
Loading history...
966
        }
967
    }
968
969
970
    /**
971
     * @param $order
972
     *
973
     * @return null
974
     */
975
    private function getNationalId($order)
976
    {
977
        foreach ((array) $order->get_meta_data() as $mdObject) {
978
            $data = $mdObject->get_data();
979
            if ($data['key'] === 'vat_number') {
980
                return $data['value'];
981
            }
982
        }
983
984
        return null;
985
    }
986
987
    /**
988
     * @param $order
989
     *
990
     * @return mixed
991
     */
992
    private function getTaxId($order)
993
    {
994
        foreach ((array) $order->get_meta_data() as $mdObject) {
995
            $data = $mdObject->get_data();
996
            if ($data['key'] === 'billing_cfpiva') {
997
                return $data['value'];
998
            }
999
        }
1000
    }
1001
1002
    /**
1003
     * @param null $exception
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $exception is correct as it would always require null to be passed?
Loading history...
1004
     * @param null $message
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $message is correct as it would always require null to be passed?
Loading history...
1005
     *
1006
     * @deprecated 8.3.7
1007
     */
1008
    private function insertLog($exception = null, $message = null)
0 ignored issues
show
Unused Code introduced by
The method insertLog() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
1009
    {
1010
        wc_deprecated_function('insertLog', '8.3.7', 'WC_Pagantis_Logger::insert_log_entry_in_wpdb');
0 ignored issues
show
Bug introduced by
The function wc_deprecated_function 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

1010
        /** @scrutinizer ignore-call */ 
1011
        wc_deprecated_function('insertLog', '8.3.7', 'WC_Pagantis_Logger::insert_log_entry_in_wpdb');
Loading history...
1011
1012
        if ($exception instanceof \Exception) {
1013
            WC_Pagantis_Logger::insert_log_entry_in_wpdb($exception);
1014
        } else {
1015
            WC_Pagantis_Logger::insert_log_entry_in_wpdb($message);
1016
        }
1017
    }
1018
1019
1020
    /**
1021
     * Check if logs table exists
1022
     *
1023
     * @deprecated 8.3.7
1024
     */
1025
    private function checkDbLogTable()
0 ignored issues
show
Unused Code introduced by
The method checkDbLogTable() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
1026
    {
1027
        wc_deprecated_function('checkDbLogTable', '8.3.7', 'pg_wc_check_db_log_table');
0 ignored issues
show
Bug introduced by
The function wc_deprecated_function 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

1027
        /** @scrutinizer ignore-call */ 
1028
        wc_deprecated_function('checkDbLogTable', '8.3.7', 'pg_wc_check_db_log_table');
Loading history...
1028
    }
1029
1030
    /**
1031
     * @param $product_id
1032
     *
1033
     * @return string
1034
     */
1035
    private function isPromoted($product_id)
1036
    {
1037
        $metaProduct = get_post_meta($product_id);
0 ignored issues
show
Bug introduced by
The function get_post_meta 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

1037
        $metaProduct = /** @scrutinizer ignore-call */ get_post_meta($product_id);
Loading history...
1038
1039
        return (array_key_exists('custom_product_pagantis_promoted', $metaProduct)
1040
                && $metaProduct['custom_product_pagantis_promoted']['0'] === 'yes') ? 'true' : 'false';
1041
    }
1042
1043
    /**
1044
     * @return int
1045
     */
1046
    private function getPromotedAmount()
1047
    {
1048
        //https://wordpress.stackexchange.com/questions/275905/whats-the-difference-between-wc-and-woocommerce
1049
        $items          = WC()->cart->get_cart();
0 ignored issues
show
Bug introduced by
The function WC 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

1049
        $items          = /** @scrutinizer ignore-call */ WC()->cart->get_cart();
Loading history...
1050
        $promotedAmount = 0;
1051
        foreach ($items as $key => $item) {
1052
            $promotedProduct = $this->isPromoted($item['product_id']);
1053
            if ($promotedProduct === 'true') {
1054
                $promotedAmount += $item['line_total'] + $item['line_tax'];
1055
            }
1056
        }
1057
1058
        return $promotedAmount;
1059
    }
1060
}
1061