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

WcPagantisGateway   F

Complexity

Total Complexity 118

Size/Duplication

Total Lines 881
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 467
c 1
b 0
f 0
dl 0
loc 881
rs 2
wmc 118

31 Methods

Rating   Name   Duplication   Size   Complexity  
A isPromoted() 0 5 3
A getKeysParametersUrl() 0 10 2
B is_available() 0 15 8
A getOkUrl() 0 3 1
A generateOkUrl() 0 3 1
A admin_options() 0 10 1
A process_payment() 0 17 3
A checkDbLogTable() 0 12 2
A getNationalId() 0 10 3
A checkDbTable() 0 12 2
A getKeysPathUrl() 0 11 3
A generateKoUrl() 0 3 1
A generateUrl() 0 16 5
A getTaxId() 0 6 3
F pagantisReceiptPage() 0 213 19
A unparseUrl() 0 9 6
A __construct() 0 38 5
A pagantisNotification() 0 30 5
A loadPagantisTranslation() 0 6 2
A pagantisCompleteStatus() 0 11 5
A getExtraConfig() 0 11 2
A getOrders() 0 36 5
A insertRow() 0 22 2
A get_title() 0 3 1
A insertLog() 0 12 2
A getKeysUrl() 0 18 3
C pagantisCheckFields() 0 29 12
A enqueue_scripts() 0 24 5
A getKoUrl() 0 3 1
A getPromotedAmount() 0 13 3
A payment_fields() 0 28 2

How to fix   Complexity   

Complex Class

Complex classes like WcPagantisGateway often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use WcPagantisGateway, and based on these observations, apply Extract Interface, too.

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
26
class WcPagantisGateway 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...
27
{
28
    const METHOD_ID = "pagantis";
29
30
    /** @var array $extraConfig */
31
    private $extraConfig;
32
33
    /** @var string $language */
34
    public $language;
35
36
    /**
37
     * WcPagantisGateway constructor.
38
     */
39
    public function __construct()
40
    {
41
        //Mandatory vars for plugin
42
        $this->id = self::METHOD_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...
43
        $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...
44
        $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...
45
        require_once dirname(__FILE__).'/../includes/class-wc-pagantis-extraconfig.php';
46
        require_once dirname(__FILE__).'/../includes/class-wc-pagantis-logger.php';
47
        //Useful vars
48
        $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

48
        $this->template_path = /** @scrutinizer ignore-call */ plugin_dir_path(__FILE__) . '../templates/';
Loading history...
49
        $this->allowed_currencies = array("EUR");
0 ignored issues
show
Bug Best Practice introduced by
The property allowed_currencies does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
50
        $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

50
        $this->language = strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true);
Loading history...
51
        if ($this->language=='') {
52
            $this->language = 'ES';
53
        }
54
        $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...
55
56
        //Panel form fields
57
        $this->form_fields = include(plugin_dir_path(__FILE__).'../includes/settings-pagantis.php');//Panel options
0 ignored issues
show
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...
58
        $this->init_settings();
59
60
        $this->extraConfig = WcPagantisExtraConfig::getExtraConfig();
61
        $this->title = __($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

61
        $this->title = /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
Loading history...
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...
62
        $this->method_description = "Financial Payment Gateway. Enable the possibility for your customers to pay their order in confortable installments with Pagantis.";
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...
63
64
        $this->settings['ok_url'] = ($this->extraConfig['PAGANTIS_URL_OK']!='')?$this->extraConfig['PAGANTIS_URL_OK']:$this->generateOkUrl();
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...
65
        $this->settings['ko_url'] = ($this->extraConfig['PAGANTIS_URL_KO']!='')?$this->extraConfig['PAGANTIS_URL_KO']:$this->generateKoUrl();
66
        foreach ($this->settings as $setting_key => $setting_value) {
67
            $this->$setting_key = $setting_value;
68
        }
69
70
        //Hooks
71
        add_action('woocommerce_update_options_payment_gateways_'.$this->id, array($this,'process_admin_options')); //Save plugin options
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

71
        /** @scrutinizer ignore-call */ 
72
        add_action('woocommerce_update_options_payment_gateways_'.$this->id, array($this,'process_admin_options')); //Save plugin options
Loading history...
72
        add_action('admin_notices', array($this, 'pagantisCheckFields'));                          //Check config fields
73
        add_action('woocommerce_receipt_'.$this->id, array($this, 'pagantisReceiptPage'));          //Pagantis form
74
        add_action('woocommerce_api_wcpagantisgateway', array($this, 'pagantisNotification'));      //Json Notification
75
        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

75
        /** @scrutinizer ignore-call */ 
76
        add_filter('woocommerce_payment_complete_order_status', array($this,'pagantisCompleteStatus'), 10, 3);
Loading history...
76
        add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
77
    }
78
79
    public function enqueue_scripts()
80
    {
81
        if ($this->enabled !== 'yes' || ! is_checkout() || is_order_received_page() || is_wc_endpoint_url('order-pay')) {
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

81
        if ($this->enabled !== 'yes' || ! /** @scrutinizer ignore-call */ is_checkout() || is_order_received_page() || is_wc_endpoint_url('order-pay')) {
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

81
        if ($this->enabled !== 'yes' || ! is_checkout() || /** @scrutinizer ignore-call */ is_order_received_page() || is_wc_endpoint_url('order-pay')) {
Loading history...
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

81
        if ($this->enabled !== 'yes' || ! is_checkout() || is_order_received_page() || /** @scrutinizer ignore-call */ is_wc_endpoint_url('order-pay')) {
Loading history...
82
            return;
83
        }
84
85
        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

85
        /** @scrutinizer ignore-call */ 
86
        wp_register_script(
Loading history...
86
            'pagantis-checkout',
87
            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

87
            /** @scrutinizer ignore-call */ 
88
            plugins_url('../assets/js/pagantis-checkout.js', __FILE__),
Loading history...
88
            array('jquery', 'woocommerce', 'wc-checkout', 'wc-country-select', 'wc-address-i18n'),
89
            PAGANTIS_VERSION,
90
            true
91
        );
92
        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

92
        /** @scrutinizer ignore-call */ 
93
        wp_enqueue_script('pagantis-checkout');
Loading history...
93
94
        $checkout_localize_params                        = array();
95
        $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...
96
        $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

96
        $checkout_localize_params['place_order_nonce']   = /** @scrutinizer ignore-call */ wp_create_nonce('pagantis_checkout');
Loading history...
97
        $checkout_localize_params['wc_ajax_url']         = WC_AJAX::get_endpoint('%%endpoint%%');
98
        $checkout_localize_params['i18n_checkout_error'] = esc_attr__('Error processing pagantis checkout. Please try again.', 'woocommerce');
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

98
        $checkout_localize_params['i18n_checkout_error'] = /** @scrutinizer ignore-call */ esc_attr__('Error processing pagantis checkout. Please try again.', 'woocommerce');
Loading history...
99
100
        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

100
        /** @scrutinizer ignore-call */ 
101
        wp_localize_script('pagantis-checkout', 'pagantis_params', $checkout_localize_params);
Loading history...
101
102
        wp_enqueue_script('pagantis_params');
103
    }
104
    /**
105
     * @param $mofile
106
     * @param $domain
107
     *
108
     * @return string
109
     */
110
    public function loadPagantisTranslation($mofile, $domain)
111
    {
112
        if ('pagantis' === $domain) {
113
            $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

113
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . /** @scrutinizer ignore-call */ get_locale() . '.mo';
Loading history...
114
        }
115
        return $mofile;
116
    }
117
118
    /***********
119
     *
120
     * HOOKS
121
     *
122
     ***********/
123
124
    /**
125
     * PANEL - Display admin panel -> Hook: woocommerce_update_options_payment_gateways_pagantis
126
     */
127
    public function admin_options()
128
    {
129
        $template_fields = array(
130
            'panel_description' => $this->method_description,
131
            '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

131
            'button1_label' => /** @scrutinizer ignore-call */ __('Login to your panel', 'pagantis'),
Loading history...
132
            'button2_label' => __('Documentation', 'pagantis'),
133
            'logo' => $this->icon,
134
            'settings' => $this->generate_settings_html($this->form_fields, false)
135
        );
136
        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

136
        /** @scrutinizer ignore-call */ 
137
        wc_get_template('admin_header.php', $template_fields, '', $this->template_path);
Loading history...
137
    }
138
139
    /**
140
     * PANEL - Check admin panel fields -> Hook: admin_notices
141
     */
142
    public function pagantisCheckFields()
143
    {
144
        $error_string = '';
145
        if ($this->settings['enabled'] !== 'yes') {
146
            return;
147
        } elseif (!version_compare(phpversion(), '5.3.0', '>=')) {
148
            $error_string =  __(' is not compatible with your php and/or curl version', '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

148
            $error_string =  /** @scrutinizer ignore-call */ __(' is not compatible with your php and/or curl version', 'pagantis');
Loading history...
149
            $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...
150
        } elseif ($this->settings['pagantis_public_key']=="" || $this->settings['pagantis_private_key']=="") {
151
            $error_string = __(' is not configured correctly, the fields Public Key and Secret Key are mandatory for use this plugin', 'pagantis');
152
            $this->settings['enabled'] = 'no';
153
        } elseif (!in_array(get_woocommerce_currency(), $this->allowed_currencies)) {
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

153
        } elseif (!in_array(/** @scrutinizer ignore-call */ get_woocommerce_currency(), $this->allowed_currencies)) {
Loading history...
154
            $error_string =  __(' only can be used in Euros', 'pagantis');
155
            $this->settings['enabled'] = 'no';
156
        } elseif ($this->extraConfig['PAGANTIS_SIMULATOR_MAX_INSTALLMENTS']<'2'
157
                  || $this->extraConfig['PAGANTIS_SIMULATOR_MAX_INSTALLMENTS']>'12') {
158
            $error_string = __(' only can be payed from 2 to 12 installments', 'pagantis');
159
        } elseif ($this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS']<'2'
160
                  || $this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS']>'12') {
161
            $error_string = __(' only can be payed from 2 to 12 installments', 'pagantis');
162
        } elseif ($this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT']<0) {
163
            $error_string = __(' can not have a minimum amount less than 0', 'pagantis');
164
        }
165
166
        if ($error_string!='') {
167
            $template_fields = array(
168
                'error_msg' => ucfirst(self::METHOD_ID).' '.$error_string,
169
            );
170
            wc_get_template('error_msg.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

170
            /** @scrutinizer ignore-call */ 
171
            wc_get_template('error_msg.php', $template_fields, '', $this->template_path);
Loading history...
171
        }
172
    }
173
174
175
    /**
176
     * CHECKOUT - Generate the pagantis form. "Return" iframe or redirect. - Hook: woocommerce_receipt_pagantis
177
     * @param $order_id
178
     *
179
     * @throws Exception
180
     */
181
    public function pagantisReceiptPage($order_id)
182
    {
183
        try {
184
            require_once(__ROOT__.'/vendor/autoload.php');
185
            global $woocommerce;
186
            $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

186
            $order = /** @scrutinizer ignore-call */ wc_get_order($order_id);
Loading history...
187
            $order->set_payment_method(ucfirst($this->id));
188
            $order->save();
189
190
            if (!isset($order)) {
191
                throw new Exception(_("Order not found"));
192
            }
193
194
            $shippingAddress = $order->get_address('shipping');
195
            $billingAddress = $order->get_address('billing');
196
            if ($shippingAddress['address_1'] == '') {
197
                $shippingAddress = $billingAddress;
198
            }
199
200
            $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 WcPagantisGateway::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...
201
            $tax_id = $this->getTaxId($order);
202
203
            $userAddress = new Address();
204
            $userAddress
205
                ->setZipCode($shippingAddress['postcode'])
206
                ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name'])
207
                ->setCountryCode($shippingAddress['country']!='' ? strtoupper($shippingAddress['country']) : strtoupper($this->language))
208
                ->setCity($shippingAddress['city'])
209
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
210
            ;
211
            $orderShippingAddress = new Address();
212
            $orderShippingAddress
213
                ->setZipCode($shippingAddress['postcode'])
214
                ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name'])
215
                ->setCountryCode($shippingAddress['country']!='' ? strtoupper($shippingAddress['country']) : strtoupper($this->language))
216
                ->setCity($shippingAddress['city'])
217
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
218
                ->setFixPhone($shippingAddress['phone'])
219
                ->setMobilePhone($shippingAddress['phone'])
220
                ->setNationalId($national_id)
221
                ->setTaxId($tax_id)
222
            ;
223
            $orderBillingAddress =  new Address();
224
            $orderBillingAddress
225
                ->setZipCode($billingAddress['postcode'])
226
                ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name'])
227
                ->setCountryCode($billingAddress['country']!='' ? strtoupper($billingAddress['country']) : strtoupper($this->language))
228
                ->setCity($billingAddress['city'])
229
                ->setAddress($billingAddress['address_1']." ".$billingAddress['address_2'])
230
                ->setFixPhone($billingAddress['phone'])
231
                ->setMobilePhone($billingAddress['phone'])
232
                ->setNationalId($national_id)
233
                ->setTaxId($tax_id)
234
            ;
235
            $orderUser = new User();
236
            $orderUser
237
                ->setAddress($userAddress)
238
                ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name'])
239
                ->setBillingAddress($orderBillingAddress)
240
                ->setEmail($billingAddress['email'])
241
                ->setFixPhone($billingAddress['phone'])
242
                ->setMobilePhone($billingAddress['phone'])
243
                ->setShippingAddress($orderShippingAddress)
244
                ->setNationalId($national_id)
245
                ->setTaxId($tax_id)
246
            ;
247
248
            $previousOrders = $this->getOrders($order->get_user(), $billingAddress['email']);
249
            foreach ($previousOrders as $previousOrder) {
250
                $orderHistory = new OrderHistory();
251
                $orderElement = wc_get_order($previousOrder);
252
                $orderCreated = $orderElement->get_date_created();
253
                $orderHistory
254
                    ->setAmount(intval(100 * $orderElement->get_total()))
255
                    ->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

255
                    ->setDate(/** @scrutinizer ignore-type */ new \DateTime($orderCreated->date('Y-m-d H:i:s')))
Loading history...
256
                ;
257
                $orderUser->addOrderHistory($orderHistory);
258
            }
259
260
            $metadataOrder = new Metadata();
261
            $metadata = array(
262
                'pg_module' => 'woocommerce',
263
                'pg_version' => PAGANTIS_VERSION,
264
                'ec_module' => 'woocommerce',
265
                '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

265
                'ec_version' => /** @scrutinizer ignore-call */ WC()->version
Loading history...
266
            );
267
268
            foreach ($metadata as $key => $metadatum) {
269
                $metadataOrder->addMetadata($key, $metadatum);
270
            }
271
272
            $details = new Details();
273
            $shippingCost = $order->shipping_total;
274
            $details->setShippingCost(intval(strval(100 * $shippingCost)));
275
            $items = $order->get_items();
276
            $promotedAmount = 0;
277
            foreach ($items as $key => $item) {
278
                $wcProduct = $item->get_product();
279
                $product = new Product();
280
                $productDescription = sprintf(
281
                    '%s %s %s',
282
                    $wcProduct->get_name(),
283
                    $wcProduct->get_description(),
284
                    $wcProduct->get_short_description()
285
                );
286
                $productDescription = substr($productDescription, 0, 9999);
287
288
                $product
289
                    ->setAmount(intval(100 * ($item->get_total() + $item->get_total_tax())))
290
                    ->setQuantity($item->get_quantity())
291
                    ->setDescription($productDescription)
292
                ;
293
                $details->addProduct($product);
294
295
                $promotedProduct = $this->isPromoted($item->get_product_id());
296
                if ($promotedProduct == 'true') {
297
                    $promotedAmount+=$product->getAmount();
298
                    $promotedMessage = 'Promoted Item: ' . $wcProduct->get_name() .
299
                                       ' - Price: ' . $item->get_total() .
300
                                       ' - Qty: ' . $product->getQuantity() .
301
                                       ' - Item ID: ' . $item['id_product'];
302
                    $promotedMessage = substr($promotedMessage, 0, 999);
303
                    $metadataOrder->addMetadata('promotedProduct', $promotedMessage);
304
                }
305
            }
306
307
            $orderShoppingCart = new ShoppingCart();
308
            $orderShoppingCart
309
                ->setDetails($details)
310
                ->setOrderReference($order->get_id())
311
                ->setPromotedAmount($promotedAmount)
312
                ->setTotalAmount(intval(strval(100 * $order->total)))
313
            ;
314
            $orderConfigurationUrls = new Urls();
315
            $cancelUrl = $this->getKoUrl($order);
316
            $callback_arg = array('wc-api'=>'wcpagantisgateway',
317
                'key'=>$order->get_order_key(),
318
                'order-received'=>$order->get_id(),
319
                'origin' => ''
320
            );
321
322
            $callback_arg_user = $callback_arg;
323
            $callback_arg_user['origin'] = 'redirect';
324
            $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

324
            $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

324
            $callback_url_user = add_query_arg($callback_arg_user, /** @scrutinizer ignore-call */ home_url('/'));
Loading history...
325
326
            $callback_arg_notif = $callback_arg;
327
            $callback_arg_notif['origin'] = 'notification';
328
            $callback_url_notif = add_query_arg($callback_arg_notif, home_url('/'));
329
330
            $orderConfigurationUrls
331
                ->setCancel($cancelUrl)
332
                ->setKo($callback_url_user)
333
                ->setAuthorizedNotificationCallback($callback_url_notif)
334
                ->setRejectedNotificationCallback(null)
335
                ->setOk($callback_url_user)
336
            ;
337
            $orderChannel = new Channel();
338
            $orderChannel
339
                ->setAssistedSale(false)
340
                ->setType(Channel::ONLINE)
341
            ;
342
343
            $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
344
            $purchaseCountry =
345
                in_array(strtolower($this->language), $allowedCountries) ? $this->language :
346
                in_array(strtolower($shippingAddress['country']), $allowedCountries) ? $shippingAddress['country'] :
347
                in_array(strtolower($billingAddress['country']), $allowedCountries) ? $billingAddress['country'] : null;
348
349
            $orderConfiguration = new Configuration();
350
            $orderConfiguration
351
                ->setChannel($orderChannel)
352
                ->setUrls($orderConfigurationUrls)
353
                ->setPurchaseCountry($purchaseCountry)
354
            ;
355
356
            $orderApiClient = new Order();
357
            $orderApiClient
358
                ->setConfiguration($orderConfiguration)
359
                ->setMetadata($metadataOrder)
360
                ->setShoppingCart($orderShoppingCart)
361
                ->setUser($orderUser)
362
            ;
363
364
            if ($this->pagantis_public_key=='' || $this->pagantis_private_key=='') {
365
                throw new \Exception('Public and Secret Key not found');
366
            }
367
            $orderClient = new Client($this->pagantis_public_key, $this->pagantis_private_key);
368
            $pagantisOrder = $orderClient->createOrder($orderApiClient);
369
            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...
370
                $url = $pagantisOrder->getActionUrls()->getForm();
371
                $this->insertRow($order->get_id(), $pagantisOrder->getId());
372
            } else {
373
                throw new OrderNotFoundException();
374
            }
375
376
            if ($url=="") {
377
                throw new Exception(_("No ha sido posible obtener una respuesta de Pagantis"));
378
            } elseif ($this->extraConfig['PAGANTIS_FORM_DISPLAY_TYPE']=='0') {
379
                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

379
                /** @scrutinizer ignore-call */ 
380
                wp_redirect($url);
Loading history...
380
                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...
381
            } else {
382
                $template_fields = array(
383
                    'url' => $url,
384
                    'checkoutUrl'   => $cancelUrl
385
                );
386
                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

386
                /** @scrutinizer ignore-call */ 
387
                wc_get_template('iframe.php', $template_fields, '', $this->template_path);
Loading history...
387
            }
388
        } catch (\Exception $exception) {
389
            wc_add_notice(__('Payment error ', 'pagantis') . $exception->getMessage(), 'error');
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

389
            wc_add_notice(/** @scrutinizer ignore-call */ __('Payment error ', 'pagantis') . $exception->getMessage(), 'error');
Loading history...
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

389
            /** @scrutinizer ignore-call */ 
390
            wc_add_notice(__('Payment error ', 'pagantis') . $exception->getMessage(), 'error');
Loading history...
390
            $this->insertLog($exception);
391
            $checkout_url = get_permalink(wc_get_page_id('checkout'));
0 ignored issues
show
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

391
            $checkout_url = get_permalink(/** @scrutinizer ignore-call */ wc_get_page_id('checkout'));
Loading history...
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

391
            $checkout_url = /** @scrutinizer ignore-call */ get_permalink(wc_get_page_id('checkout'));
Loading history...
392
            wp_redirect($checkout_url);
393
            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...
394
        }
395
    }
396
397
    /**
398
     * NOTIFICATION - Endpoint for Json notification - Hook: woocommerce_api_wcpagantisgateway
399
     */
400
    public function pagantisNotification()
401
    {
402
        try {
403
            $origin = ($_SERVER['REQUEST_METHOD'] == 'POST') ? 'Notify' : 'Order';
404
405
            include_once('notifyController.php');
406
            $notify = new WcPagantisNotify();
407
            $notify->setOrigin($origin);
408
            /** @var \Pagantis\ModuleUtils\Model\Response\AbstractJsonResponse $result */
409
            $result = $notify->processInformation();
410
        } catch (Exception $exception) {
411
            $result['notification_message'] = $exception->getMessage();
412
            $result['notification_error'] = true;
413
        }
414
415
        $paymentOrder = new WC_Order($result->getMerchantOrderId());
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...
416
        if ($paymentOrder instanceof WC_Order) {
417
            $orderStatus = strtolower($paymentOrder->get_status());
418
        } else {
419
            $orderStatus = 'cancelled';
420
        }
421
        $acceptedStatus = array('processing', 'completed');
422
        if (in_array($orderStatus, $acceptedStatus)) {
423
            $returnUrl = $this->getOkUrl($paymentOrder);
424
        } else {
425
            $returnUrl = $this->getKoUrl($paymentOrder);
426
        }
427
428
        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

428
        /** @scrutinizer ignore-call */ 
429
        wp_redirect($returnUrl);
Loading history...
429
        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...
430
    }
431
432
    /**
433
     * After failed status, set to processing not complete -> Hook: woocommerce_payment_complete_order_status
434
     * @param $status
435
     * @param $order_id
436
     * @param $order
437
     *
438
     * @return string
439
     */
440
    public function pagantisCompleteStatus($status, $order_id, $order)
441
    {
442
        if ($order->get_payment_method() == self::METHOD_ID) {
443
            if ($order->get_status() == 'failed') {
444
                $status = 'processing';
445
            } elseif ($order->get_status() == 'pending' && $status=='completed') {
446
                $status = 'processing';
447
            }
448
        }
449
450
        return $status;
451
    }
452
453
    /***********
454
     *
455
     * REDEFINED FUNCTIONS
456
     *
457
     ***********/
458
459
    /**
460
     * CHECKOUT - Check if payment method is available (called by woocommerce, can't apply cammel caps)
461
     * @return bool
462
     */
463
    public function is_available()
464
    {
465
        $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

465
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
466
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
467
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
468
        $minAmount = $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'];
469
        $maxAmount = $this->extraConfig['PAGANTIS_DISPLAY_MAX_AMOUNT'];
470
        $totalPrice = (int)$this->get_order_total();
471
        $validAmount = ($totalPrice>=$minAmount && ($totalPrice<=$maxAmount || $maxAmount=='0'));
472
        if ($this->enabled==='yes' && $this->pagantis_public_key!='' && $this->pagantis_private_key!='' &&
473
            $validAmount && $allowedCountry) {
474
            return true;
475
        }
476
477
        return false;
478
    }
479
480
    /**
481
     * CHECKOUT - Checkout + admin panel title(method_title - get_title) (called by woocommerce,can't apply cammel caps)
482
     * @return string
483
     */
484
    public function get_title()
485
    {
486
        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

486
        return /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
Loading history...
487
    }
488
489
    /**
490
     * CHECKOUT - Called after push pagantis button on checkout(called by woocommerce, can't apply cammel caps
491
     * @param $order_id
492
     * @return array
493
     */
494
    public function process_payment($order_id)
495
    {
496
        try {
497
            $order = new WC_Order($order_id);
498
499
            $redirectUrl = $order->get_checkout_payment_url(true); //pagantisReceiptPage function
500
            if (strpos($redirectUrl, 'order-pay=')===false) {
501
                $redirectUrl.="&order-pay=".$order_id;
502
            }
503
504
            return array(
505
                'result'   => 'success',
506
                'redirect' => $redirectUrl
507
            );
508
        } catch (Exception $e) {
509
            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

509
            /** @scrutinizer ignore-call */ 
510
            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

509
            wc_add_notice(/** @scrutinizer ignore-call */ __('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
510
            return array();
511
        }
512
    }
513
514
    /**
515
     * CHECKOUT - simulator (called by woocommerce, can't apply cammel caps)
516
     */
517
    public function payment_fields()
518
    {
519
        $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

519
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
520
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
521
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
522
        $promotedAmount = $this->getPromotedAmount();
523
524
        $template_fields = array(
525
            'public_key' => $this->pagantis_public_key,
526
            '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

526
            'total' => /** @scrutinizer ignore-call */ WC()->cart->get_total(),
Loading history...
527
            'enabled' =>  $this->settings['enabled'],
528
            'min_installments' => $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'],
529
            'max_installments' => $this->extraConfig['PAGANTIS_DISPLAY_MAX_AMOUNT'],
530
            'simulator_enabled' => $this->settings['simulator'],
531
            'locale' => $locale,
532
            'country' => $locale,
533
            'allowed_country' => $allowedCountry,
534
            'simulator_type' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE_CHECKOUT'],
535
            'promoted_amount' => $promotedAmount,
536
            'thousandSeparator' => $this->extraConfig['PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'],
537
            'decimalSeparator' => $this->extraConfig['PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR'],
538
            'pagantisSimulatorSkin' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_SKIN']
539
        );
540
        try {
541
            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

541
            /** @scrutinizer ignore-call */ 
542
            wc_get_template('checkout_description.php', $template_fields, '', $this->template_path);
Loading history...
542
        } catch (Exception $exception) {
543
            $exception->getMessage();
544
            var_export($exception->getMessage());
545
        }
546
    }
547
548
    /***********
549
     *
550
     * UTILS FUNCTIONS
551
     *
552
     ***********/
553
554
    /**
555
     * PANEL KO_URL FIELD
556
     * CHECKOUT PAGE => ?page_id=91 // ORDER-CONFIRMATION PAGE => ?page_id=91&order-pay=<order_id>&key=<order_key>
557
     */
558
    private function generateOkUrl()
559
    {
560
        return $this->generateUrl($this->get_return_url());
561
    }
562
563
    /**
564
     * PANEL OK_URL FIELD
565
     */
566
    private function generateKoUrl()
567
    {
568
        return $this->generateUrl(get_permalink(wc_get_page_id('checkout')));
0 ignored issues
show
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

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

568
        return $this->generateUrl(/** @scrutinizer ignore-call */ get_permalink(wc_get_page_id('checkout')));
Loading history...
569
    }
570
571
    /**
572
     * Replace empty space by {{var}}
573
     * @param $url
574
     *
575
     * @return string
576
     */
577
    private function generateUrl($url)
578
    {
579
        $parsed_url = parse_url($url);
580
        if ($parsed_url !== false) {
581
            $parsed_url['query'] = !isset($parsed_url['query']) ? '' : $parsed_url['query'];
582
            parse_str($parsed_url['query'], $arrayParams);
583
            foreach ($arrayParams as $keyParam => $valueParam) {
584
                if ($valueParam=='') {
585
                    $arrayParams[$keyParam] = '{{'.$keyParam.'}}';
586
                }
587
            }
588
            $parsed_url['query'] = http_build_query($arrayParams);
589
            $return_url = $this->unparseUrl($parsed_url);
590
            return urldecode($return_url);
591
        } else {
592
            return $url;
593
        }
594
    }
595
596
    /**
597
     * Replace {{}} by vars values inside ok_url
598
     * @param $order
599
     *
600
     * @return string
601
     */
602
    private function getOkUrl($order)
603
    {
604
        return $this->getKeysUrl($order, $this->ok_url);
605
    }
606
607
    /**
608
     * Replace {{}} by vars values inside ko_url
609
     * @param $order
610
     *
611
     * @return string
612
     */
613
    private function getKoUrl($order)
614
    {
615
        return $this->getKeysUrl($order, $this->ko_url);
616
    }
617
618
    /**
619
     * Replace {{}} by vars values
620
     * @param $order
621
     * @param $url
622
     *
623
     * @return string
624
     */
625
    private function getKeysUrl($order, $url)
626
    {
627
        $defaultFields = (get_class($order)=='WC_Order') ?
628
            array('order-received'=>$order->get_id(), 'key'=>$order->get_order_key()) :
629
            array();
630
631
        $parsedUrl = parse_url($url);
632
        if ($parsedUrl !== false) {
633
            //Replace parameters from url
634
            $parsedUrl['query'] = $this->getKeysParametersUrl($parsedUrl['query'], $defaultFields);
635
636
            //Replace path from url
637
            $parsedUrl['path'] = $this->getKeysPathUrl($parsedUrl['path'], $defaultFields);
638
639
            $returnUrl = $this->unparseUrl($parsedUrl);
640
            return $returnUrl;
641
        }
642
        return $url;
643
    }
644
645
    /**
646
     * Replace {{}} by vars values inside parameters
647
     * @param $queryString
648
     * @param $defaultFields
649
     *
650
     * @return string
651
     */
652
    private function getKeysParametersUrl($queryString, $defaultFields)
653
    {
654
        parse_str(html_entity_decode($queryString), $arrayParams);
655
        $commonKeys = array_intersect_key($arrayParams, $defaultFields);
656
        if (count($commonKeys)) {
657
            $arrayResult = array_merge($arrayParams, $defaultFields);
658
        } else {
659
            $arrayResult = $arrayParams;
660
        }
661
        return urldecode(http_build_query($arrayResult));
662
    }
663
664
    /**
665
     * Replace {{}} by vars values inside path
666
     * @param $pathString
667
     * @param $defaultFields
668
     *
669
     * @return string
670
     */
671
    private function getKeysPathUrl($pathString, $defaultFields)
672
    {
673
        $arrayParams = explode("/", $pathString);
674
        foreach ($arrayParams as $keyParam => $valueParam) {
675
            preg_match('#\{{.*?}\}#', $valueParam, $match);
676
            if (count($match)) {
677
                $key = str_replace(array('{{','}}'), array('',''), $match[0]);
678
                $arrayParams[$keyParam] = $defaultFields[$key];
679
            }
680
        }
681
        return implode('/', $arrayParams);
682
    }
683
684
    /**
685
     * Replace {{var}} by empty space
686
     * @param $parsed_url
687
     *
688
     * @return string
689
     */
690
    private function unparseUrl($parsed_url)
691
    {
692
        $scheme   = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
693
        $host     = isset($parsed_url['host']) ? $parsed_url['host'] : '';
694
        $port     = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
695
        $query    = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
696
        $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
697
        $path     = $parsed_url['path'];
698
        return $scheme . $host . $port . $path . $query . $fragment;
699
    }
700
701
    /**
702
     * Get the orders of a customer
703
     * @param $current_user
704
     * @param $billingEmail
705
     *
706
     * @return mixed
707
     */
708
    private function getOrders($current_user, $billingEmail)
709
    {
710
        $sign_up = '';
711
        $total_orders = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $total_orders is dead and can be removed.
Loading history...
712
        $total_amt = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $total_amt is dead and can be removed.
Loading history...
713
        $refund_amt = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $refund_amt is dead and can be removed.
Loading history...
714
        $total_refunds = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $total_refunds is dead and can be removed.
Loading history...
715
        $partial_refunds = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $partial_refunds is dead and can be removed.
Loading history...
716
        if ($current_user->user_login) {
717
            $is_guest = "false";
0 ignored issues
show
Unused Code introduced by
The assignment to $is_guest is dead and can be removed.
Loading history...
718
            $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...
719
            $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

719
            $customer_orders = /** @scrutinizer ignore-call */ get_posts(array(
Loading history...
720
                'numberposts' => - 1,
721
                'meta_key'    => '_customer_user',
722
                'meta_value'  => $current_user->ID,
723
                'post_type'   => array( 'shop_order' ),
724
                'post_status' => array( 'wc-completed', 'wc-processing', 'wc-refunded' ),
725
            ));
726
        } else {
727
            $is_guest = "true";
728
            $customer_orders = get_posts(array(
729
                'numberposts' => - 1,
730
                'meta_key'    => '_billing_email',
731
                'meta_value'  => $billingEmail,
732
                'post_type'   => array( 'shop_order' ),
733
                'post_status' => array( 'wc-completed', 'wc-processing', 'wc-refunded'),
734
            ));
735
            foreach ($customer_orders as $customer_order) {
736
                if (trim($sign_up)=='' ||
737
                    strtotime(substr($customer_order->post_date, 0, 10)) <= strtotime($sign_up)) {
738
                    $sign_up = substr($customer_order->post_date, 0, 10);
739
                }
740
            }
741
        }
742
743
        return $customer_orders;
744
    }
745
746
747
    /**
748
     * @param $orderId
749
     * @param $pagantisOrderId
750
     *
751
     * @throws Exception
752
     */
753
    private function insertRow($orderId, $pagantisOrderId)
754
    {
755
        global $wpdb;
756
        $this->checkDbTable();
757
        $tableName = $wpdb->prefix.PAGANTIS_WC_ORDERS_TABLE;
758
759
        //Check if id exists
760
        $resultsSelect = $wpdb->get_results("select * from $tableName where id='$orderId'");
761
        $countResults = count($resultsSelect);
762
        if ($countResults == 0) {
763
            $wpdb->insert(
764
                $tableName,
765
                array('id' => $orderId, 'order_id' => $pagantisOrderId),
766
                array('%d', '%s')
767
            );
768
        } else {
769
            $wpdb->update(
770
                $tableName,
771
                array('order_id' => $pagantisOrderId),
772
                array('id' => $orderId),
773
                array('%s'),
774
                array('%d')
775
            );
776
        }
777
    }
778
779
    /**
780
     * Check if orders table exists
781
     */
782
    private function checkDbTable()
783
    {
784
        global $wpdb;
785
        $tableName = $wpdb->prefix.PAGANTIS_WC_ORDERS_TABLE;
786
787
        if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName) {
788
            $charset_collate = $wpdb->get_charset_collate();
789
            $sql             = "CREATE TABLE $tableName ( id int, order_id varchar(50), wc_order_id varchar(50),  
790
                  UNIQUE KEY id (id)) $charset_collate";
791
792
            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...
793
            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

793
            /** @scrutinizer ignore-call */ 
794
            dbDelta($sql);
Loading history...
794
        }
795
    }
796
797
    /**
798
     * @return array
799
     */
800
    private function getExtraConfig()
801
    {
802
        global $wpdb;
803
        $tableName = $wpdb->prefix.PAGANTIS_CONFIG_TABLE;
804
        $response = array();
805
        $dbResult = $wpdb->get_results("select config, value from $tableName", ARRAY_A);
0 ignored issues
show
Bug introduced by
The constant ARRAY_A was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
806
        foreach ($dbResult as $value) {
807
            $response[$value['config']] = $value['value'];
808
        }
809
810
        return $response;
811
    }
812
813
    /**
814
     * @param $order
815
     *
816
     * @return null
817
     */
818
    private function getNationalId($order)
819
    {
820
        foreach ((array)$order->get_meta_data() as $mdObject) {
821
            $data = $mdObject->get_data();
822
            if ($data['key'] == 'vat_number') {
823
                return $data['value'];
824
            }
825
        }
826
827
        return null;
828
    }
829
830
    /**
831
     * @param $order
832
     *
833
     * @return mixed
834
     */
835
    private function getTaxId($order)
836
    {
837
        foreach ((array)$order->get_meta_data() as $mdObject) {
838
            $data = $mdObject->get_data();
839
            if ($data['key'] == 'billing_cfpiva') {
840
                return $data['value'];
841
            }
842
        }
843
    }
844
845
    /**
846
     * @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...
847
     * @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...
848
     */
849
    private function insertLog($exception = null, $message = null)
850
    {
851
        global $wpdb;
852
        $this->checkDbLogTable();
853
        $logEntry     = new LogEntry();
854
        if ($exception instanceof \Exception) {
855
            $logEntry = $logEntry->error($exception);
856
        } else {
857
            $logEntry = $logEntry->info($message);
858
        }
859
        $tableName = $wpdb->prefix.PAGANTIS_LOGS_TABLE;
860
        $wpdb->insert($tableName, array('log' => $logEntry->toJson()));
861
    }
862
    /**
863
     * Check if logs table exists
864
     */
865
    private function checkDbLogTable()
866
    {
867
        global $wpdb;
868
        $tableName = $wpdb->prefix.PAGANTIS_LOGS_TABLE;
869
        if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName) {
870
            $charset_collate = $wpdb->get_charset_collate();
871
            $sql = "CREATE TABLE $tableName ( id int NOT NULL AUTO_INCREMENT, log text NOT NULL, 
872
                    createdAt timestamp DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY id (id)) $charset_collate";
873
            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...
874
            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

874
            /** @scrutinizer ignore-call */ 
875
            dbDelta($sql);
Loading history...
875
        }
876
        return;
877
    }
878
879
    /**
880
     * @param $product_id
881
     *
882
     * @return string
883
     */
884
    private function isPromoted($product_id)
885
    {
886
        $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

886
        $metaProduct = /** @scrutinizer ignore-call */ get_post_meta($product_id);
Loading history...
887
        return (array_key_exists('custom_product_pagantis_promoted', $metaProduct) &&
888
                $metaProduct['custom_product_pagantis_promoted']['0'] === 'yes') ? 'true' : 'false';
889
    }
890
891
    /**
892
     * @return int
893
     */
894
    private function getPromotedAmount()
895
    {
896
        global $woocommerce;
897
        $items = $woocommerce->cart->get_cart();
898
        $promotedAmount = 0;
899
        foreach ($items as $key => $item) {
900
            $promotedProduct = $this->isPromoted($item['product_id']);
901
            if ($promotedProduct == 'true') {
902
                $promotedAmount+=$item['line_total'] + $item['line_tax'];
903
            }
904
        }
905
906
        return $promotedAmount;
907
    }
908
}
909