Completed
Push — master ( bcf6c3...37bd96 )
by
unknown
13s queued 10s
created

WcPagantisGateway::checkDbLogTable()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 12
rs 9.9666
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
18
if (!defined('ABSPATH')) {
19
    exit;
20
}
21
22
if (!defined('__ROOT__')) {
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
    const NOT_CONFIRMED = 'No se ha podido confirmar el pago';
31
32
    /** @var array $extraConfig */
33
    public $extraConfig;
34
35
    /** @var string $language */
36
    public $language;
37
38
    /**
39
     * @var string $template_path
40
     */
41
42
    private $template_path;
43
    /**
44
     * @var array $allowed_currencies
45
     */
46
    private $allowed_currencies;
47
48
    /**
49
     * WcPagantisGateway constructor.
50
     */
51
    public function __construct()
52
    {
53
        //Mandatory vars for plugin
54
        $this->id = WcPagantisGateway::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...
55
        $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...
56
        $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...
57
58
        //Useful vars
59
        $this->template_path = plugin_dir_path(__FILE__) . '../templates/';
0 ignored issues
show
Bug introduced by
The function plugin_dir_path was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

59
        $this->template_path = /** @scrutinizer ignore-call */ plugin_dir_path(__FILE__) . '../templates/';
Loading history...
60
        $this->allowed_currencies = getAllowedCurrencies();
61
        $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

61
        $this->language = strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true);
Loading history...
62
        if ($this->language=='') {
63
            $this->language = 'ES';
64
        }
65
        $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...
66
67
        //Panel form fields
68
        $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...
69
        $this->init_settings();
70
71
        $this->extraConfig = getExtraConfig();
72
        $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

72
        $this->title = /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
Loading history...
73
        $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...
74
75
        $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...
76
        $this->settings['ko_url'] = ($this->extraConfig['PAGANTIS_URL_KO']!='')?$this->extraConfig['PAGANTIS_URL_KO']:$this->generateKoUrl();
77
        foreach ($this->settings as $setting_key => $setting_value) {
78
            $this->$setting_key = $setting_value;
79
        }
80
81
        //Hooks
82
        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

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

86
        /** @scrutinizer ignore-call */ 
87
        add_filter('woocommerce_payment_complete_order_status', array($this,'pagantisCompleteStatus'), 10, 3);
Loading history...
87
        add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
88
    }
89
90
    /**
91
     * @param $mofile
92
     * @param $domain
93
     *
94
     * @return string
95
     */
96
    public function loadPagantisTranslation($mofile, $domain)
97
    {
98
        if ('pagantis' === $domain) {
99
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . get_locale() . '.mo';
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

99
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . /** @scrutinizer ignore-call */ get_locale() . '.mo';
Loading history...
Bug introduced by
The constant WP_LANG_DIR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
100
        }
101
        return $mofile;
102
    }
103
104
    /***********
105
     *
106
     * HOOKS
107
     *
108
     ***********/
109
110
    /**
111
     * PANEL - Display admin panel
112
     * @hooked woocommerce_update_options_payment_gateways_pagantis
113
     */
114
    public function admin_options()
115
    {
116
        $template_fields = array(
117
            'panel_description' => $this->method_description,
118
            '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

118
            'button1_label' => /** @scrutinizer ignore-call */ __('Login to your panel', 'pagantis'),
Loading history...
119
            'button2_label' => __('Documentation', 'pagantis'),
120
            'logo' => $this->icon,
121
            'settings' => $this->generate_settings_html($this->form_fields, false)
122
        );
123
        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

123
        /** @scrutinizer ignore-call */ 
124
        wc_get_template('admin_header.php', $template_fields, '', $this->template_path);
Loading history...
124
    }
125
126
    /**
127
     * PANEL - Check admin panel fields
128
     * @hooked  admin_notices
129
     */
130
    public function pagantisCheckFields()
131
    {
132
        $error_string = '';
133
        if ($this->settings['enabled'] !== 'yes') {
134
            return;
135
        } elseif (!version_compare(phpversion(), '5.3.0', '>=')) {
136
            $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

136
            $error_string =  /** @scrutinizer ignore-call */ __(' is not compatible with your php and/or curl version', 'pagantis');
Loading history...
137
            $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...
138
        } elseif (($this->settings['pagantis_public_key']=="" || $this->settings['pagantis_private_key']=="")  && (empty($this->settings['pagantis_public_key_4x']) || empty($this->settings['pagantis_private_key_4x']))) {
139
            $error_string = __(' is not configured correctly, the fields Public Key and Secret Key are mandatory for use this plugin', 'pagantis');
140
            $this->settings['enabled'] = 'no';
141
        } 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

141
        } elseif (!in_array(/** @scrutinizer ignore-call */ get_woocommerce_currency(), $this->allowed_currencies)) {
Loading history...
142
            $error_string =  __(' only can be used in Euros', 'pagantis');
143
            $this->settings['enabled'] = 'no';
144
        } elseif ($this->extraConfig['PAGANTIS_SIMULATOR_MAX_INSTALLMENTS']<'2'
145
                  || $this->extraConfig['PAGANTIS_SIMULATOR_MAX_INSTALLMENTS']>'12') {
146
            $error_string = __(' only can be payed from 2 to 12 installments', 'pagantis');
147
        } elseif ($this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS']<'2'
148
                  || $this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS']>'12') {
149
            $error_string = __(' only can be payed from 2 to 12 installments', 'pagantis');
150
        } elseif ($this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT']<0) {
151
            $error_string = __(' can not have a minimum amount less than 0', 'pagantis');
152
        }
153
154
        if ($error_string!='') {
155
            $template_fields = array(
156
                'error_msg' => ucfirst(WcPagantisGateway::METHOD_ID).' '.$error_string,
157
            );
158
            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

158
            /** @scrutinizer ignore-call */ 
159
            wc_get_template('error_msg.php', $template_fields, '', $this->template_path);
Loading history...
159
        }
160
    }
161
162
163
    /**
164
     * CHECKOUT - Generate the pagantis form. "Return" iframe or redirect.
165
     * @param $order_id
166
     *
167
     * @hooked woocommerce_receipt_pagantis
168
     * @throws Exception
169
     */
170
    public function pagantisReceiptPage($order_id)
171
    {
172
        try {
173
            require_once(__ROOT__.'/vendor/autoload.php');
174
            $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...
175
            $order->set_payment_method(ucfirst($this->id));
176
            $order->save();
177
178
            if (!isset($order)) {
179
                throw new Exception(_("Order not found"));
180
            }
181
182
            $shippingAddress = $order->get_address('shipping');
183
            $billingAddress = $order->get_address('billing');
184
            if ($shippingAddress['address_1'] == '') {
185
                $shippingAddress = $billingAddress;
186
            }
187
188
            $national_id = getNationalId($order);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $national_id is correct as getNationalId($order) 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...
189
            $tax_id = getTaxId($order);
190
191
            $userAddress = new Address();
192
            $userAddress
193
                ->setZipCode($shippingAddress['postcode'])
194
                ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name'])
195
                ->setCountryCode($shippingAddress['country']!='' ? strtoupper($shippingAddress['country']) : strtoupper($this->language))
196
                ->setCity($shippingAddress['city'])
197
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
198
            ;
199
            $orderShippingAddress = new Address();
200
            $orderShippingAddress
201
                ->setZipCode($shippingAddress['postcode'])
202
                ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name'])
203
                ->setCountryCode($shippingAddress['country']!='' ? strtoupper($shippingAddress['country']) : strtoupper($this->language))
204
                ->setCity($shippingAddress['city'])
205
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
206
                ->setFixPhone($shippingAddress['phone'])
207
                ->setMobilePhone($shippingAddress['phone'])
208
                ->setNationalId($national_id)
209
                ->setTaxId($tax_id)
210
            ;
211
            $orderBillingAddress =  new Address();
212
            $orderBillingAddress
213
                ->setZipCode($billingAddress['postcode'])
214
                ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name'])
215
                ->setCountryCode($billingAddress['country']!='' ? strtoupper($billingAddress['country']) : strtoupper($this->language))
216
                ->setCity($billingAddress['city'])
217
                ->setAddress($billingAddress['address_1']." ".$billingAddress['address_2'])
218
                ->setFixPhone($billingAddress['phone'])
219
                ->setMobilePhone($billingAddress['phone'])
220
                ->setNationalId($national_id)
221
                ->setTaxId($tax_id)
222
            ;
223
            $orderUser = new User();
224
            $orderUser
225
                ->setAddress($userAddress)
226
                ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name'])
227
                ->setBillingAddress($orderBillingAddress)
228
                ->setEmail($billingAddress['email'])
229
                ->setFixPhone($billingAddress['phone'])
230
                ->setMobilePhone($billingAddress['phone'])
231
                ->setShippingAddress($orderShippingAddress)
232
                ->setNationalId($national_id)
233
                ->setTaxId($tax_id)
234
            ;
235
236
            $previousOrders = getOrders($order->get_user(), $billingAddress['email']);
237
            foreach ($previousOrders as $previousOrder) {
238
                $orderHistory = new OrderHistory();
239
                $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

239
                $orderElement = /** @scrutinizer ignore-call */ wc_get_order($previousOrder);
Loading history...
240
                $orderCreated = $orderElement->get_date_created();
241
                $orderHistory
242
                    ->setAmount(intval(100 * $orderElement->get_total()))
243
                    ->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

243
                    ->setDate(/** @scrutinizer ignore-type */ new \DateTime($orderCreated->date('Y-m-d H:i:s')))
Loading history...
244
                ;
245
                $orderUser->addOrderHistory($orderHistory);
246
            }
247
248
            $metadataOrder = new Metadata();
249
            $metadata = array(
250
                'pg_module' => 'woocommerce',
251
                'pg_version' => PG_VERSION,
252
                'ec_module' => 'woocommerce',
253
                '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

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

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

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

369
                /** @scrutinizer ignore-call */ 
370
                wp_redirect($url);
Loading history...
370
                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...
371
            } else {
372
                // @todo TM refactor with wp_localize_script - maybe put in other function
373
                $template_fields = array(
374
                    'url' => $url,
375
                    'checkoutUrl'   => $cancelUrl
376
                );
377
                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

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

380
            /** @scrutinizer ignore-call */ 
381
            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

380
            wc_add_notice(/** @scrutinizer ignore-call */ __('Payment error ', 'pagantis') . $exception->getMessage(), 'error');
Loading history...
381
            insertLogEntry($exception);
382
            $checkout_url = get_permalink(wc_get_page_id('checkout'));
0 ignored issues
show
Bug introduced by
The function get_permalink was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

382
            $checkout_url = /** @scrutinizer ignore-call */ get_permalink(wc_get_page_id('checkout'));
Loading history...
Bug introduced by
The function wc_get_page_id was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

420
        /** @scrutinizer ignore-call */ 
421
        wp_redirect($returnUrl);
Loading history...
421
        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...
422
    }
423
424
    /**
425
     * After failed status, set to processing not complete -> Hook: woocommerce_payment_complete_order_status
426
     * @param $status
427
     * @param $order_id
428
     * @param $order
429
     *
430
     * @return string
431
     */
432
    public function pagantisCompleteStatus($status, $order_id, $order)
433
    {
434
        if ($order->get_payment_method() == WcPagantisGateway::METHOD_ID) {
435
            if ($order->get_status() == 'failed') {
436
                $status = 'processing';
437
            } elseif ($order->get_status() == 'pending' && $status=='completed') {
438
                $status = 'processing';
439
            }
440
        }
441
442
        return $status;
443
    }
444
445
    /***********
446
     *
447
     * REDEFINED FUNCTIONS
448
     *
449
     ***********/
450
451
    /**
452
     * CHECKOUT - Check if payment method is available
453
     * @see WC_Payment_Gateway::is_available()
454
     * @return bool
455
     */
456
    public function is_available()
457
    {
458
        $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

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

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

505
            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

505
            /** @scrutinizer ignore-call */ 
506
            wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
506
            return array();
507
        }
508
    }
509
510
    /**
511
     * CHECKOUT - simulator
512
     * @see WC_Payment_Gateway::payment_fields()
513
     */
514
    public function payment_fields()
515
    {
516
        $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

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

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

540
        /** @scrutinizer ignore-call */ 
541
        wc_get_template('checkout_description.php', $template_fields, '', $this->template_path);
Loading history...
541
    }
542
543
    /***********
544
     *
545
     * UTILS FUNCTIONS
546
     *
547
     ***********/
548
549
    /**
550
     * PANEL KO_URL FIELD
551
     * CHECKOUT PAGE => ?page_id=91 // ORDER-CONFIRMATION PAGE => ?page_id=91&order-pay=<order_id>&key=<order_key>
552
     */
553
    private function generateOkUrl()
554
    {
555
        return $this->generateUrl($this->get_return_url());
556
    }
557
558
    /**
559
     * PANEL OK_URL FIELD
560
     */
561
    private function generateKoUrl()
562
    {
563
        return $this->generateUrl(get_permalink(wc_get_page_id('checkout')));
0 ignored issues
show
Bug introduced by
The function get_permalink was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

563
        return $this->generateUrl(/** @scrutinizer ignore-call */ get_permalink(wc_get_page_id('checkout')));
Loading history...
Bug introduced by
The function wc_get_page_id was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

563
        return $this->generateUrl(get_permalink(/** @scrutinizer ignore-call */ wc_get_page_id('checkout')));
Loading history...
564
    }
565
566
    /**
567
     * Replace empty space by {{var}}
568
     * @param $url
569
     *
570
     * @return string
571
     */
572
    private function generateUrl($url)
573
    {
574
        $parsed_url = parse_url($url);
575
        if ($parsed_url !== false) {
576
            $parsed_url['query'] = !isset($parsed_url['query']) ? '' : $parsed_url['query'];
577
            parse_str($parsed_url['query'], $arrayParams);
578
            foreach ($arrayParams as $keyParam => $valueParam) {
579
                if ($valueParam=='') {
580
                    $arrayParams[$keyParam] = '{{'.$keyParam.'}}';
581
                }
582
            }
583
            $parsed_url['query'] = http_build_query($arrayParams);
584
            $return_url = $this->unparseUrl($parsed_url);
585
            return urldecode($return_url);
586
        } else {
587
            return $url;
588
        }
589
    }
590
591
    /**
592
     * Replace {{}} by vars values inside ok_url
593
     * @param $order
594
     *
595
     * @return string
596
     */
597
    private function getOkUrl($order)
598
    {
599
        return $this->getKeysUrl($order, $this->ok_url);
600
    }
601
602
    /**
603
     * Replace {{}} by vars values inside ko_url
604
     * @param $order
605
     *
606
     * @return string
607
     */
608
    private function getKoUrl($order)
609
    {
610
        return $this->getKeysUrl($order, $this->ko_url);
611
    }
612
613
    /**
614
     * Replace {{}} by vars values
615
     * @param $order
616
     * @param $url
617
     *
618
     * @return string
619
     */
620
    private function getKeysUrl($order, $url)
621
    {
622
        $defaultFields = (get_class($order)=='WC_Order') ?
623
            array('order-received'=>$order->get_id(), 'key'=>$order->get_order_key()) :
624
            array();
625
626
        $parsedUrl = parse_url($url);
627
        if ($parsedUrl !== false) {
628
            //Replace parameters from url
629
            $parsedUrl['query'] = $this->getKeysParametersUrl($parsedUrl['query'], $defaultFields);
630
631
            //Replace path from url
632
            $parsedUrl['path'] = $this->getKeysPathUrl($parsedUrl['path'], $defaultFields);
633
634
            $returnUrl = $this->unparseUrl($parsedUrl);
635
            return $returnUrl;
636
        }
637
        return $url;
638
    }
639
640
    /**
641
     * Replace {{}} by vars values inside parameters
642
     * @param $queryString
643
     * @param $defaultFields
644
     *
645
     * @return string
646
     */
647
    private function getKeysParametersUrl($queryString, $defaultFields)
648
    {
649
        parse_str(html_entity_decode($queryString), $arrayParams);
650
        $commonKeys = array_intersect_key($arrayParams, $defaultFields);
651
        if (count($commonKeys)) {
652
            $arrayResult = array_merge($arrayParams, $defaultFields);
653
        } else {
654
            $arrayResult = $arrayParams;
655
        }
656
        return urldecode(http_build_query($arrayResult));
657
    }
658
659
    /**
660
     * Replace {{}} by vars values inside path
661
     * @param $pathString
662
     * @param $defaultFields
663
     *
664
     * @return string
665
     */
666
    private function getKeysPathUrl($pathString, $defaultFields)
667
    {
668
        $arrayParams = explode("/", $pathString);
669
        foreach ($arrayParams as $keyParam => $valueParam) {
670
            preg_match('#\{{.*?}\}#', $valueParam, $match);
671
            if (count($match)) {
672
                $key = str_replace(array('{{','}}'), array('',''), $match[0]);
673
                $arrayParams[$keyParam] = $defaultFields[$key];
674
            }
675
        }
676
        return implode('/', $arrayParams);
677
    }
678
679
    /**
680
     * Replace {{var}} by empty space
681
     * @param $parsed_url
682
     *
683
     * @return string
684
     */
685
    private function unparseUrl($parsed_url)
686
    {
687
        $scheme   = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
688
        $host     = isset($parsed_url['host']) ? $parsed_url['host'] : '';
689
        $port     = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
690
        $query    = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
691
        $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
692
        $path     = $parsed_url['path'];
693
        return $scheme . $host . $port . $path . $query . $fragment;
694
    }
695
}
696