WcPagantisGateway::loadPagantisTranslation()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 6
rs 10
1
<?php
2
3
//namespace empty
4
use Pagantis\ModuleUtils\Exception\OrderNotFoundException;
5
use Pagantis\OrdersApiClient\Model\Order\User\Address;
6
use Pagantis\OrdersApiClient\Model\Order\User;
7
use Pagantis\OrdersApiClient\Model\Order\User\OrderHistory;
8
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details;
9
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart;
10
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product;
11
use Pagantis\OrdersApiClient\Model\Order\Metadata;
12
use Pagantis\OrdersApiClient\Model\Order\Configuration\Urls;
13
use Pagantis\OrdersApiClient\Model\Order\Configuration\Channel;
14
use Pagantis\OrdersApiClient\Model\Order\Configuration;
15
use Pagantis\OrdersApiClient\Client;
16
use Pagantis\OrdersApiClient\Model\Order;
17
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
     * @var string
50
     */
51
    private $urlToken;
52
53
    /**
54
     * WcPagantisGateway constructor.
55
     */
56
    public function __construct()
57
    {
58
        require_once(plugin_dir_path(__FILE__).'../includes/pg-functions.php');
0 ignored issues
show
Bug introduced by
The function plugin_dir_path was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

58
        require_once(/** @scrutinizer ignore-call */ plugin_dir_path(__FILE__).'../includes/pg-functions.php');
Loading history...
59
        //Mandatory vars for plugin
60
        $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...
61
        $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...
62
        $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...
63
        $this->urlToken = strtoupper(md5(uniqid(rand(), true)));
64
65
        //Useful vars
66
        $this->template_path = plugin_dir_path(__FILE__) . '../templates/';
67
        $this->allowed_currencies = getAllowedCurrencies();
68
        $this->mainFileLocation = dirname(plugin_dir_path(__FILE__)) . '/WC_Pagantis.php';
0 ignored issues
show
Bug Best Practice introduced by
The property mainFileLocation does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
69
        $this->plugin_info = get_file_data($this->mainFileLocation, array('Version' => 'Version'), false);
0 ignored issues
show
Bug introduced by
The function get_file_data 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

69
        $this->plugin_info = /** @scrutinizer ignore-call */ get_file_data($this->mainFileLocation, array('Version' => 'Version'), false);
Loading history...
Bug Best Practice introduced by
The property plugin_info does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
70
        $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

70
        $this->language = strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true);
Loading history...
71
        if ($this->language=='') {
72
            $this->language = 'ES';
73
        }
74
        $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...
75
76
        //Panel form fields
77
        $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...
78
        $this->init_settings();
79
80
        $this->extraConfig = getExtraConfig();
81
        $this->title = __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

81
        $this->title = /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
Loading history...
Bug Best Practice introduced by
The property title does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
82
        $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...
83
84
        $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...
85
        $this->settings['ko_url'] = ($this->extraConfig['PAGANTIS_URL_KO']!='')?$this->extraConfig['PAGANTIS_URL_KO']:$this->generateKoUrl();
86
        foreach ($this->settings as $setting_key => $setting_value) {
87
            $this->$setting_key = $setting_value;
88
        }
89
90
        //Hooks
91
        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

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

95
        /** @scrutinizer ignore-call */ 
96
        add_filter('woocommerce_payment_complete_order_status', array($this,'pagantisCompleteStatus'), 10, 3);
Loading history...
96
        add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
97
    }
98
99
    /**
100
     * @param $mofile
101
     * @param $domain
102
     *
103
     * @return string
104
     */
105
    public function loadPagantisTranslation($mofile, $domain)
106
    {
107
        if ('pagantis' === $domain) {
108
            $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

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

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

132
        /** @scrutinizer ignore-call */ 
133
        wc_get_template('admin_header.php', $template_fields, '', $this->template_path);
Loading history...
133
    }
134
135
    /**
136
     * PANEL - Check admin panel fields
137
     * @hooked  admin_notices
138
     */
139
    public function pagantisCheckFields()
140
    {
141
        $error_string = '';
142
        if ($this->settings['enabled'] !== 'yes') {
143
            return;
144
        } elseif (!version_compare(phpversion(), '5.3.0', '>=')) {
145
            $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

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

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

167
            /** @scrutinizer ignore-call */ 
168
            wc_get_template('error_msg.php', $template_fields, '', $this->template_path);
Loading history...
168
        }
169
    }
170
171
172
    /**
173
     * CHECKOUT - Generate the pagantis form. "Return" iframe or redirect.
174
     * @param $order_id
175
     *
176
     * @hooked woocommerce_receipt_pagantis
177
     * @throws Exception
178
     */
179
    public function pagantisReceiptPage($order_id)
180
    {
181
        try {
182
            require_once(__ROOT__.'/vendor/autoload.php');
183
            $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...
184
            $order->set_payment_method(ucfirst($this->id));
185
            $order->save();
186
            if (!isset($order)) {
187
                throw new Exception(_("Order not found"));
188
            }
189
190
            $shippingAddress = $order->get_address('shipping');
191
            $billingAddress = $order->get_address('billing');
192
            if ($shippingAddress['address_1'] == '') {
193
                $shippingAddress = $billingAddress;
194
            }
195
196
            $customer_id = $order->get_customer_id();
197
            $national_id = maybeGetIDNumber($order , $customer_id);
198
            $tax_id = maybeGetTaxIDNumber($order , $customer_id);
199
            $phoneNumber = maybeGetPhoneNumber($order , $customer_id);
200
201
            $userAddress = new Address();
202
            $userAddress
203
                ->setZipCode($shippingAddress['postcode'])
204
                ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name'])
205
                ->setCountryCode($shippingAddress['country']!='' ? strtoupper($shippingAddress['country']) : strtoupper($this->language))
206
                ->setCity($shippingAddress['city'])
207
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
208
                ->setDni($national_id)
209
            ;
210
            $orderShippingAddress = new Address();
211
            $orderShippingAddress
212
                ->setZipCode($shippingAddress['postcode'])
213
                ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name'])
214
                ->setCountryCode($shippingAddress['country']!='' ? strtoupper($shippingAddress['country']) : strtoupper($this->language))
215
                ->setCity($shippingAddress['city'])
216
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
217
                ->setFixPhone($phoneNumber)
218
                ->setMobilePhone($phoneNumber)
219
                ->setNationalId($national_id)
220
                ->setDni($national_id)
221
                ->setTaxId($tax_id)
222
            ;
223
            $orderBillingAddress =  new Address();
224
            $orderBillingAddress
225
                ->setZipCode($billingAddress['postcode'])
226
                ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name'])
227
                ->setCountryCode($billingAddress['country']!='' ? strtoupper($billingAddress['country']) : strtoupper($this->language))
228
                ->setCity($billingAddress['city'])
229
                ->setAddress($billingAddress['address_1']." ".$billingAddress['address_2'])
230
                ->setFixPhone($phoneNumber)
231
                ->setMobilePhone($phoneNumber)
232
                ->setNationalId($national_id)
233
                ->setTaxId($tax_id)
234
            ;
235
            $orderUser = new User();
236
            $orderUser
237
                ->setAddress($userAddress)
238
                ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name'])
239
                ->setBillingAddress($orderBillingAddress)
240
                ->setEmail($billingAddress['email'])
241
                ->setFixPhone($phoneNumber)
242
                ->setMobilePhone($phoneNumber)
243
                ->setShippingAddress($orderShippingAddress)
244
                ->setNationalId($national_id)
245
                ->setTaxId($tax_id)
246
            ;
247
248
            if (!empty(maybeGetDateOfBirth($customer_id))) {
249
                $orderUser->setDateOfBirth($birthday);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $birthday seems to be never defined.
Loading history...
250
            }
251
            $previousOrders = 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' => getModuleVersion(),
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 = isProductPromoted($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
                'token' => $this->urlToken
324
            );
325
326
            $callback_arg_user = $callback_arg;
327
            $callback_arg_user['origin'] = 'redirect';
328
            $callback_arg_user['product'] = Ucfirst(WcPagantisGateway::METHOD_ID);
329
            $callback_url_user = add_query_arg($callback_arg_user, home_url('/'));
0 ignored issues
show
Bug introduced by
The function add_query_arg was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

329
            $callback_url_user = /** @scrutinizer ignore-call */ add_query_arg($callback_arg_user, home_url('/'));
Loading history...
Bug introduced by
The function home_url was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

392
                /** @scrutinizer ignore-call */ 
393
                wc_get_template('iframe.php', $template_fields, '', $this->template_path);
Loading history...
393
            }
394
        } catch (\Exception $exception) {
395
            wc_add_notice(__('Payment error ', 'pagantis') . $exception->getMessage(), 'error');
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

395
            wc_add_notice(/** @scrutinizer ignore-call */ __('Payment error ', 'pagantis') . $exception->getMessage(), 'error');
Loading history...
Bug introduced by
The function wc_add_notice was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

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

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

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

495
        return /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
Loading history...
496
    }
497
498
    /**
499
     * CHECKOUT - Called after push pagantis button on checkout
500
     * @param $order_id
501
     *
502
     * @return array
503
     * @see WC_Payment_Gateway::process_payment()
504
     */
505
    public function process_payment($order_id)
506
    {
507
        try {
508
            $order = new WC_Order($order_id);
509
510
            $redirectUrl = $order->get_checkout_payment_url(true); //pagantisReceiptPage function
511
            if (strpos($redirectUrl, 'order-pay=')===false) {
512
                $redirectUrl.="&order-pay=".$order_id;
513
            }
514
515
            return array(
516
                'result'   => 'success',
517
                'redirect' => $redirectUrl
518
            );
519
        } catch (Exception $e) {
520
            wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
0 ignored issues
show
Bug introduced by
The function wc_add_notice was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

520
            /** @scrutinizer ignore-call */ 
521
            wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

520
            wc_add_notice(/** @scrutinizer ignore-call */ __('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
521
            return array();
522
        }
523
    }
524
525
    /**
526
     * CHECKOUT - simulator
527
     * @see WC_Payment_Gateway::payment_fields()
528
     */
529
    public function payment_fields()
530
    {
531
        $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

531
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
532
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
533
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
534
        $promotedAmount = getPromotedAmount();
535
536
        $template_fields = array(
537
            'public_key' => $this->pagantis_public_key,
538
            '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

538
            'total' => /** @scrutinizer ignore-call */ WC()->session->cart_totals['total'],
Loading history...
539
            'enabled' =>  $this->settings['enabled'],
540
            'min_installments' => $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'],
541
            'max_installments' => $this->extraConfig['PAGANTIS_DISPLAY_MAX_AMOUNT'],
542
            'simulator_enabled' => $this->settings['simulator'],
543
            'locale' => $locale,
544
            'country' => $locale,
545
            'allowed_country' => $allowedCountry,
546
            'simulator_type' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE_CHECKOUT'],
547
            'promoted_amount' => $promotedAmount,
548
            'thousandSeparator' => $this->extraConfig['PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'],
549
            'decimalSeparator' => $this->extraConfig['PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR'],
550
            'pagantisSimulatorSkin' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_SKIN']
551
        );
552
553
554
        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

554
        /** @scrutinizer ignore-call */ 
555
        wc_get_template('checkout_description.php', $template_fields, '', $this->template_path);
Loading history...
555
    }
556
557
    /***********
558
     *
559
     * UTILS FUNCTIONS
560
     *
561
     ***********/
562
563
    /**
564
     * PANEL KO_URL FIELD
565
     * CHECKOUT PAGE => ?page_id=91 // ORDER-CONFIRMATION PAGE => ?page_id=91&order-pay=<order_id>&key=<order_key>
566
     */
567
    private function generateOkUrl()
568
    {
569
        return $this->generateUrl($this->get_return_url());
570
    }
571
572
    /**
573
     * PANEL OK_URL FIELD
574
     */
575
    private function generateKoUrl()
576
    {
577
        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

577
        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

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