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

WcPagantis4xGateway::insertLog()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 9
c 1
b 0
f 0
nc 2
nop 2
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 WcPagantis4xGateway 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 = "pagantis4x";
29
30
31
32
    const NOT_CONFIRMED = 'No se ha podido confirmar el pago';
33
34
35
    /** @var array $extraConfig */
36
    public $extraConfig;
37
38
    /** @var string $language */
39
    public $language;
40
41
    /**
42
     * @var string $template_path
43
     */
44
45
    private $template_path;
46
    /**
47
     * @var array $allowed_currencies
48
     */
49
    private $allowed_currencies;
50
51
52
    /**
53
     * WcPagantis4xGateway constructor.
54
     */
55
    public function __construct()
56
    {
57
        //Mandatory vars for plugin
58
        $this->id = WcPagantis4xGateway::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...
59
        $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...
60
        $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...
61
62
        //Useful vars
63
        $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

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

65
        $this->language = strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true);
Loading history...
66
        if ($this->language=='') {
67
            $this->language = 'ES';
68
        }
69
        $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...
70
71
        //Panel form fields
72
        $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...
73
        $this->init_settings();
74
75
        $this->extraConfig = getExtraConfig();
76
        $this->title = __($this->extraConfig['PAGANTIS_TITLE_4x'], '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

76
        $this->title = /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE_4x'], '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...
77
        $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...
78
79
        $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...
80
        $this->settings['ko_url'] = ($this->extraConfig['PAGANTIS_URL_KO']!='')?$this->extraConfig['PAGANTIS_URL_KO']:$this->generateKoUrl();
81
        foreach ($this->settings as $setting_key => $setting_value) {
82
            $this->$setting_key = $setting_value;
83
        }
84
85
        //Hooks
86
        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

86
        /** @scrutinizer ignore-call */ 
87
        add_action('woocommerce_update_options_payment_gateways_'.$this->id, array($this,'process_admin_options')); //Save plugin options
Loading history...
87
        add_action('woocommerce_receipt_'.$this->id, array($this, 'pagantisReceiptPage'));          //Pagantis form
88
        add_action('woocommerce_api_wcpagantisgateway', array($this, 'pagantisNotification'));      //Json Notification
89
        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

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

102
            $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...
103
        }
104
        return $mofile;
105
    }
106
107
    /***********
108
     *
109
     * HOOKS
110
     *
111
     ***********/
112
113
    /**
114
     * PANEL - Display admin panel
115
     * @hooked woocommerce_update_options_payment_gateways_pagantis
116
     */
117
    public function admin_options()
118
    {
119
        $template_fields = array(
120
            'panel_description' => $this->method_description,
121
            '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

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

126
        /** @scrutinizer ignore-call */ 
127
        wc_get_template('admin_header.php', $template_fields, '', $this->template_path);
Loading history...
127
    }
128
129
    /**
130
     * CHECKOUT - Generate the pagantis form. "Return" iframe or redirect.
131
     * @param $order_id
132
     *
133
     * @throws Exception
134
     * @hooked woocommerce_receipt_pagantis
135
     */
136
    public function pagantisReceiptPage($order_id)
137
    {
138
        try {
139
            require_once(__ROOT__.'/vendor/autoload.php');
140
            global $woocommerce;
141
            $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...
142
            $order->set_payment_method(ucfirst($this->id));
143
            $order->save();
144
145
            if (!isset($order)) {
146
                throw new Exception(_("Order not found"));
147
            }
148
149
            $shippingAddress = $order->get_address('shipping');
150
            $billingAddress = $order->get_address('billing');
151
            if ($shippingAddress['address_1'] == '') {
152
                $shippingAddress = $billingAddress;
153
            }
154
155
            $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...
156
            $tax_id = getTaxId($order);
157
158
            $userAddress = new Address();
159
            $userAddress
160
                ->setZipCode($shippingAddress['postcode'])
161
                ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name'])
162
                ->setCountryCode($shippingAddress['country']!='' ? strtoupper($shippingAddress['country']) : strtoupper($this->language))
163
                ->setCity($shippingAddress['city'])
164
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
165
            ;
166
            $orderShippingAddress = new Address();
167
            $orderShippingAddress
168
                ->setZipCode($shippingAddress['postcode'])
169
                ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name'])
170
                ->setCountryCode($shippingAddress['country']!='' ? strtoupper($shippingAddress['country']) : strtoupper($this->language))
171
                ->setCity($shippingAddress['city'])
172
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
173
                ->setFixPhone($shippingAddress['phone'])
174
                ->setMobilePhone($shippingAddress['phone'])
175
                ->setNationalId($national_id)
176
                ->setTaxId($tax_id)
177
            ;
178
            $orderBillingAddress =  new Address();
179
            $orderBillingAddress
180
                ->setZipCode($billingAddress['postcode'])
181
                ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name'])
182
                ->setCountryCode($billingAddress['country']!='' ? strtoupper($billingAddress['country']) : strtoupper($this->language))
183
                ->setCity($billingAddress['city'])
184
                ->setAddress($billingAddress['address_1']." ".$billingAddress['address_2'])
185
                ->setFixPhone($billingAddress['phone'])
186
                ->setMobilePhone($billingAddress['phone'])
187
                ->setNationalId($national_id)
188
                ->setTaxId($tax_id)
189
            ;
190
            $orderUser = new User();
191
            $orderUser
192
                ->setAddress($userAddress)
193
                ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name'])
194
                ->setBillingAddress($orderBillingAddress)
195
                ->setEmail($billingAddress['email'])
196
                ->setFixPhone($billingAddress['phone'])
197
                ->setMobilePhone($billingAddress['phone'])
198
                ->setShippingAddress($orderShippingAddress)
199
                ->setNationalId($national_id)
200
                ->setTaxId($tax_id)
201
            ;
202
203
            $previousOrders = getOrders($order->get_user(), $billingAddress['email']);
204
            foreach ($previousOrders as $previousOrder) {
205
                $orderHistory = new OrderHistory();
206
                $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

206
                $orderElement = /** @scrutinizer ignore-call */ wc_get_order($previousOrder);
Loading history...
207
                $orderCreated = $orderElement->get_date_created();
208
                $orderHistory
209
                    ->setAmount(intval(100 * $orderElement->get_total()))
210
                    ->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

210
                    ->setDate(/** @scrutinizer ignore-type */ new \DateTime($orderCreated->date('Y-m-d H:i:s')))
Loading history...
211
                ;
212
                $orderUser->addOrderHistory($orderHistory);
213
            }
214
215
            $metadataOrder = new Metadata();
216
            $metadata = array(
217
                'pg_module' => 'woocommerce',
218
                'pg_version' => PG_VERSION,
219
                'ec_module' => 'woocommerce',
220
                '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

220
                'ec_version' => /** @scrutinizer ignore-call */ WC()->version
Loading history...
221
            );
222
223
            foreach ($metadata as $key => $metadatum) {
224
                $metadataOrder->addMetadata($key, $metadatum);
225
            }
226
227
            $details = new Details();
228
            $shippingCost = $order->shipping_total;
229
            $details->setShippingCost(intval(strval(100 * $shippingCost)));
230
            $items = $order->get_items();
231
            $promotedAmount = 0;
232
            foreach ($items as $key => $item) {
233
                $wcProduct = $item->get_product();
234
                $product = new Product();
235
                $productDescription = sprintf(
236
                    '%s %s %s',
237
                    $wcProduct->get_name(),
238
                    $wcProduct->get_description(),
239
                    $wcProduct->get_short_description()
240
                );
241
                $productDescription = substr($productDescription, 0, 9999);
242
243
                $product
244
                    ->setAmount(intval(100 * ($item->get_total() + $item->get_total_tax())))
245
                    ->setQuantity($item->get_quantity())
246
                    ->setDescription($productDescription)
247
                ;
248
                $details->addProduct($product);
249
250
                $promotedProduct = isProductPromoted($item->get_product_id());
251
                if ($promotedProduct == 'true') {
252
                    $promotedAmount+=$product->getAmount();
253
                    $promotedMessage = 'Promoted Item: ' . $wcProduct->get_name() .
254
                                       ' - Price: ' . $item->get_total() .
255
                                       ' - Qty: ' . $product->getQuantity() .
256
                                       ' - Item ID: ' . $item['id_product'];
257
                    $promotedMessage = substr($promotedMessage, 0, 999);
258
                    $metadataOrder->addMetadata('promotedProduct', $promotedMessage);
259
                }
260
            }
261
262
            $orderShoppingCart = new ShoppingCart();
263
            $orderShoppingCart
264
                ->setDetails($details)
265
                ->setOrderReference($order->get_id())
266
                ->setPromotedAmount($promotedAmount)
267
                ->setTotalAmount(intval(strval(100 * $order->total)))
268
            ;
269
            $orderConfigurationUrls = new Urls();
270
            $cancelUrl = $this->getKoUrl($order);
271
            $callback_arg = array('wc-api'=>'wcpagantisgateway',
272
                                  'key'=>$order->get_order_key(),
273
                                  'order-received'=>$order->get_id(),
274
                                  'origin' => ''
275
            );
276
277
            $callback_arg_user = $callback_arg;
278
            $callback_arg_user['origin'] = 'redirect';
279
            $callback_arg_user['product'] = Ucfirst(WcPagantis4xGateway::METHOD_ID);
280
            $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

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

280
            $callback_url_user = /** @scrutinizer ignore-call */ add_query_arg($callback_arg_user, home_url('/'));
Loading history...
281
282
            $callback_arg_notif = $callback_arg;
283
            $callback_arg_notif['origin'] = 'notification';
284
            $callback_arg_notif['product'] = Ucfirst(WcPagantis4xGateway::METHOD_ID);
285
            $callback_url_notif = add_query_arg($callback_arg_notif, home_url('/'));
286
287
            $orderConfigurationUrls
288
                ->setCancel($cancelUrl)
289
                ->setKo($callback_url_user)
290
                ->setAuthorizedNotificationCallback($callback_url_notif)
291
                ->setRejectedNotificationCallback(null)
292
                ->setOk($callback_url_user)
293
            ;
294
            $orderChannel = new Channel();
295
            $orderChannel
296
                ->setAssistedSale(false)
297
                ->setType(Channel::ONLINE)
298
            ;
299
300
            $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
301
            $purchaseCountry =
302
                in_array(strtolower($this->language), $allowedCountries) ? $this->language :
303
                    in_array(strtolower($shippingAddress['country']), $allowedCountries) ? $shippingAddress['country'] :
304
                        in_array(strtolower($billingAddress['country']), $allowedCountries) ? $billingAddress['country'] : null;
305
306
            $orderConfiguration = new Configuration();
307
            $orderConfiguration
308
                ->setChannel($orderChannel)
309
                ->setUrls($orderConfigurationUrls)
310
                ->setPurchaseCountry($purchaseCountry)
311
            ;
312
313
            $orderApiClient = new Order();
314
            $orderApiClient
315
                ->setConfiguration($orderConfiguration)
316
                ->setMetadata($metadataOrder)
317
                ->setShoppingCart($orderShoppingCart)
318
                ->setUser($orderUser)
319
            ;
320
321
            $cfg = get_option('woocommerce_pagantis_settings');
0 ignored issues
show
Bug introduced by
The function get_option 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

321
            $cfg = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
322
            if ($cfg['pagantis_public_key_4x']=='' || $cfg['pagantis_private_key_4x']=='') {
323
                throw new \Exception('Public and Secret Key not found');
324
            }
325
            $orderClient = new Client($cfg['pagantis_public_key_4x'], $cfg['pagantis_private_key_4x']);
326
            $pagantisOrder = $orderClient->createOrder($orderApiClient);
327
            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...
328
                $url = $pagantisOrder->getActionUrls()->getForm();
329
                addOrderToCartProcessingQueue($order->get_id(), $pagantisOrder->getId());
330
            } else {
331
                throw new OrderNotFoundException();
332
            }
333
334
            if ($url=="") {
335
                throw new Exception(_("No ha sido posible obtener una respuesta de Pagantis"));
336
            } elseif ($this->extraConfig['PAGANTIS_FORM_DISPLAY_TYPE']=='0') {
337
                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

337
                /** @scrutinizer ignore-call */ 
338
                wp_redirect($url);
Loading history...
338
                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...
339
            } else {
340
                // @todo TM refactor with wp_localize_script - maybe put in other function
341
                $template_fields = array(
342
                    'url' => $url,
343
                    'checkoutUrl'   => $cancelUrl
344
                );
345
                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

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

348
            /** @scrutinizer ignore-call */ 
349
            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

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

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

350
            $checkout_url = get_permalink(/** @scrutinizer ignore-call */ wc_get_page_id('checkout'));
Loading history...
351
            wp_redirect($checkout_url);
352
            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...
353
        }
354
    }
355
356
    /**
357
     * NOTIFICATION - Endpoint for Json notification
358
     *
359
     * @hooked woocommerce_api_wcpagantisgateway
360
     */
361
    public function pagantisNotification()
362
    {
363
        try {
364
            $origin = ($_SERVER['REQUEST_METHOD'] == 'POST') ? 'Notify' : 'Order';
365
366
            include_once('notifyController.php');
367
            $notify = new WcPagantisNotify();
368
            $notify->setOrigin($origin);
369
            /** @var \Pagantis\ModuleUtils\Model\Response\AbstractJsonResponse $result */
370
            $result = $notify->processInformation();
371
        } catch (Exception $exception) {
372
            $result['notification_message'] = $exception->getMessage();
373
            $result['notification_error'] = true;
374
        }
375
376
        $paymentOrder = new WC_Order($result->getMerchantOrderId());
377
        if ($paymentOrder instanceof WC_Order) {
378
            $orderStatus = strtolower($paymentOrder->get_status());
379
        } else {
380
            $orderStatus = 'cancelled';
381
        }
382
        $acceptedStatus = array('processing', 'completed');
383
        if (in_array($orderStatus, $acceptedStatus)) {
384
            $returnUrl = $this->getOkUrl($paymentOrder);
385
        } else {
386
            $returnUrl = $this->getKoUrl($paymentOrder);
387
        }
388
389
        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

389
        /** @scrutinizer ignore-call */ 
390
        wp_redirect($returnUrl);
Loading history...
390
        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...
391
    }
392
393
    /**
394
     * After failed status, set to processing not complete -> Hook: woocommerce_payment_complete_order_status
395
     * @param $status
396
     * @param $order_id
397
     * @param $order
398
     *
399
     * @return string
400
     */
401
    public function pagantisCompleteStatus($status, $order_id, $order)
402
    {
403
        if ($order->get_payment_method() == WcPagantis4xGateway::METHOD_ID) {
404
            if ($order->get_status() == 'failed') {
405
                $status = 'processing';
406
            } elseif ($order->get_status() == 'pending' && $status=='completed') {
407
                $status = 'processing';
408
            }
409
        }
410
411
        return $status;
412
    }
413
414
    /***********
415
     *
416
     * REDEFINED FUNCTIONS
417
     *
418
     ***********/
419
420
421
    /**
422
     * CHECKOUT - Check if payment method is available
423
     *
424
     * @return bool
425
     * @see WC_Payment_Gateway::is_available()
426
     */
427
    public function is_available()
428
    {
429
        $cfg = get_option('woocommerce_pagantis_settings');
0 ignored issues
show
Bug introduced by
The function get_option 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

429
        $cfg = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
430
        $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

430
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
431
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
432
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
433
        $minAmount = $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT_4x'];
434
        $maxAmount = $this->extraConfig['PAGANTIS_DISPLAY_MAX_AMOUNT_4x'];
435
        $totalPrice = (int)$this->get_order_total();
436
        $validAmount = ($totalPrice>=$minAmount && ($totalPrice<=$maxAmount || $maxAmount=='0'));
437
        if ($cfg['enabled_4x']==='yes' && $cfg['pagantis_public_key_4x']!='' && $cfg['pagantis_private_key_4x']!='' &&
438
            $validAmount && $allowedCountry) {
439
            return true;
440
        }
441
442
        return false;
443
    }
444
445
    /**
446
     * CHECKOUT - Checkout + admin panel title(method_title - get_title)
447
     *
448
     * @return string
449
     * @see WC_Payment_Gateway::get_title()
450
     */
451
    public function get_title()
452
    {
453
        return __($this->extraConfig['PAGANTIS_TITLE_4x'], '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

453
        return /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE_4x'], 'pagantis');
Loading history...
454
    }
455
456
    /**
457
     * CHECKOUT - Called after push pagantis button on checkout
458
     *
459
     * @param $order_id
460
     *
461
     * @return array
462
     * @see WC_Payment_Gateway::process_payment()
463
     */
464
    public function process_payment($order_id)
465
    {
466
        try {
467
            $order = new WC_Order($order_id);
468
469
            $redirectUrl = $order->get_checkout_payment_url(true); //pagantisReceiptPage function
470
            if (strpos($redirectUrl, 'order-pay=')===false) {
471
                $redirectUrl.="&order-pay=".$order_id;
472
            }
473
474
            return array(
475
                'result'   => 'success',
476
                'redirect' => $redirectUrl
477
            );
478
        } catch (Exception $e) {
479
            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

479
            /** @scrutinizer ignore-call */ 
480
            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

479
            wc_add_notice(/** @scrutinizer ignore-call */ __('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
480
            return array();
481
        }
482
    }
483
484
    /**
485
     * CHECKOUT - simulator
486
     *
487
     * @see WC_Payment_Gateway::payment_fields()
488
     */
489
    public function payment_fields()
490
    {
491
        $cfg = get_option('woocommerce_pagantis_settings');
0 ignored issues
show
Bug introduced by
The function get_option 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

491
        $cfg = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
492
        $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

492
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
493
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
494
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
495
        $promotedAmount = getPromotedAmount();
496
497
        $template_fields = array(
498
            'public_key' => $cfg['pagantis_public_key_4x'],
499
            '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

499
            'total' => /** @scrutinizer ignore-call */ WC()->session->cart_totals['total'],
Loading history...
500
            'enabled' =>  $cfg['enabled_4x'],
501
            'min_installments' => $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT_4x'],
502
            'max_installments' => $this->extraConfig['PAGANTIS_DISPLAY_MAX_AMOUNT_4x'],
503
            'simulator_enabled' => "yes",
504
            'locale' => $locale,
505
            'country' => $locale,
506
            'allowed_country' => $allowedCountry,
507
            'simulator_type' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE_CHECKOUT'],
508
            'promoted_amount' => $promotedAmount,
509
            'thousandSeparator' => $this->extraConfig['PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'],
510
            'decimalSeparator' => $this->extraConfig['PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR'],
511
            'pagantisSimulatorSkin' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_SKIN'],
512
            'product' => '4x'
513
        );
514
515
        wc_get_template('checkout_description4x.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

515
        /** @scrutinizer ignore-call */ 
516
        wc_get_template('checkout_description4x.php', $template_fields, '', $this->template_path);
Loading history...
516
    }
517
518
    /***********
519
     *
520
     * UTILS FUNCTIONS
521
     *
522
     ***********/
523
524
    /**
525
     * PANEL KO_URL FIELD
526
     * CHECKOUT PAGE => ?page_id=91 // ORDER-CONFIRMATION PAGE => ?page_id=91&order-pay=<order_id>&key=<order_key>
527
     */
528
    private function generateOkUrl()
529
    {
530
        return $this->generateUrl($this->get_return_url());
531
    }
532
533
    /**
534
     * PANEL OK_URL FIELD
535
     */
536
    private function generateKoUrl()
537
    {
538
        return $this->generateUrl(get_permalink(wc_get_page_id('checkout')));
0 ignored issues
show
Bug introduced by
The function wc_get_page_id was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

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