Passed
Pull Request — master (#48)
by
unknown
04:00
created

WcPagantisGateway::enqueue_scripts()   A

Complexity

Conditions 5
Paths 2

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 16
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 24
rs 9.4222
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
    public $extraConfig;
32
33
    /** @var string $language */
34
    public $language;
35
36
37
    /**
38
     * WcPagantisGateway constructor.
39
     */
40
    public function __construct()
41
    {
42
        //Mandatory vars for plugin
43
        $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...
44
        $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...
45
        $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...
46
        include_once dirname(__FILE__).'/../includes/class-wc-pagantis-extraconfig.php';
47
        include_once dirname(__FILE__).'/../includes/class-wc-pagantis-logger.php';
48
        $value = WcPagantisExtraConfig::getExtraConfigValue('PAGANTIS_TITLE');
49
        WCPagantisLogger::writeLog($value);
50
        //Useful vars
51
        $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

51
        $this->template_path = /** @scrutinizer ignore-call */ plugin_dir_path(__FILE__) . '../templates/';
Loading history...
52
        $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...
53
        $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

53
        $this->language = strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true);
Loading history...
54
        if ($this->language=='') {
55
            $this->language = 'ES';
56
        }
57
        $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...
58
59
        //Panel form fields
60
        $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...
61
        $this->init_settings();
62
63
        $this->extraConfig = $this->getExtraConfig();
64
        $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

64
        $this->title = /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
Loading history...
65
        $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...
66
67
        $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...
68
        $this->settings['ko_url'] = ($this->extraConfig['PAGANTIS_URL_KO']!='')?$this->extraConfig['PAGANTIS_URL_KO']:$this->generateKoUrl();
69
        foreach ($this->settings as $setting_key => $setting_value) {
70
            $this->$setting_key = $setting_value;
71
        }
72
73
        //Hooks
74
        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

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

78
        /** @scrutinizer ignore-call */ 
79
        add_filter('woocommerce_payment_complete_order_status', array($this,'pagantisCompleteStatus'), 10, 3);
Loading history...
79
        add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
80
    }
81
82
    public function enqueue_scripts()
83
    {
84
        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_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

84
        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_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

84
        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_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

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

88
        /** @scrutinizer ignore-call */ 
89
        wp_register_script(
Loading history...
89
            'pagantis-checkout',
90
            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

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

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

99
        $checkout_localize_params['place_order_nonce']   = /** @scrutinizer ignore-call */ wp_create_nonce('pagantis_checkout');
Loading history...
100
        $checkout_localize_params['wc_ajax_url']         = WC_AJAX::get_endpoint('%%endpoint%%');
101
        $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

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

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

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

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

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

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

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

173
            /** @scrutinizer ignore-call */ 
174
            wc_get_template('error_msg.php', $template_fields, '', $this->template_path);
Loading history...
174
        }
175
    }
176
177
178
    /**
179
     * CHECKOUT - Generate the pagantis form. "Return" iframe or redirect. - Hook: woocommerce_receipt_pagantis
180
     * @param $order_id
181
     *
182
     * @throws Exception
183
     */
184
    public function pagantisReceiptPage($order_id)
185
    {
186
        try {
187
            require_once(__ROOT__.'/vendor/autoload.php');
188
            global $woocommerce;
189
            $order = new WC_Order($order_id);
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...
190
            $order->set_payment_method(ucfirst($this->id));
191
            $order->save();
192
193
            if (!isset($order)) {
194
                throw new Exception(_("Order not found"));
195
            }
196
197
            $shippingAddress = $order->get_address('shipping');
198
            $billingAddress = $order->get_address('billing');
199
            if ($shippingAddress['address_1'] == '') {
200
                $shippingAddress = $billingAddress;
201
            }
202
203
            $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...
204
            $tax_id = $this->getTaxId($order);
205
206
            $userAddress = new Address();
207
            $userAddress
208
                ->setZipCode($shippingAddress['postcode'])
209
                ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name'])
210
                ->setCountryCode($shippingAddress['country']!='' ? strtoupper($shippingAddress['country']) : strtoupper($this->language))
211
                ->setCity($shippingAddress['city'])
212
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
213
            ;
214
            $orderShippingAddress = new Address();
215
            $orderShippingAddress
216
                ->setZipCode($shippingAddress['postcode'])
217
                ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name'])
218
                ->setCountryCode($shippingAddress['country']!='' ? strtoupper($shippingAddress['country']) : strtoupper($this->language))
219
                ->setCity($shippingAddress['city'])
220
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
221
                ->setFixPhone($shippingAddress['phone'])
222
                ->setMobilePhone($shippingAddress['phone'])
223
                ->setNationalId($national_id)
224
                ->setTaxId($tax_id)
225
            ;
226
            $orderBillingAddress =  new Address();
227
            $orderBillingAddress
228
                ->setZipCode($billingAddress['postcode'])
229
                ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name'])
230
                ->setCountryCode($billingAddress['country']!='' ? strtoupper($billingAddress['country']) : strtoupper($this->language))
231
                ->setCity($billingAddress['city'])
232
                ->setAddress($billingAddress['address_1']." ".$billingAddress['address_2'])
233
                ->setFixPhone($billingAddress['phone'])
234
                ->setMobilePhone($billingAddress['phone'])
235
                ->setNationalId($national_id)
236
                ->setTaxId($tax_id)
237
            ;
238
            $orderUser = new User();
239
            $orderUser
240
                ->setAddress($userAddress)
241
                ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name'])
242
                ->setBillingAddress($orderBillingAddress)
243
                ->setEmail($billingAddress['email'])
244
                ->setFixPhone($billingAddress['phone'])
245
                ->setMobilePhone($billingAddress['phone'])
246
                ->setShippingAddress($orderShippingAddress)
247
                ->setNationalId($national_id)
248
                ->setTaxId($tax_id)
249
            ;
250
251
            $previousOrders = $this->getOrders($order->get_user(), $billingAddress['email']);
252
            foreach ($previousOrders as $previousOrder) {
253
                $orderHistory = new OrderHistory();
254
                $orderElement = wc_get_order($previousOrder);
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

254
                $orderElement = /** @scrutinizer ignore-call */ wc_get_order($previousOrder);
Loading history...
255
                $orderCreated = $orderElement->get_date_created();
256
                $orderHistory
257
                    ->setAmount(intval(100 * $orderElement->get_total()))
258
                    ->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

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

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

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

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

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

389
                /** @scrutinizer ignore-call */ 
390
                wc_get_template('iframe.php', $template_fields, '', $this->template_path);
Loading history...
390
            }
391
        } catch (\Exception $exception) {
392
            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

392
            /** @scrutinizer ignore-call */ 
393
            wc_add_notice(__('Payment error ', 'pagantis') . $exception->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

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

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

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

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

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

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

512
            wc_add_notice(/** @scrutinizer ignore-call */ __('Payment error ', 'pagantis') . $e->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

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

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

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

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

566
        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

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

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

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

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

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