Passed
Pull Request — master (#13)
by
unknown
02:21
created

WcPagantisGateway::pagantisReceiptPage()   F

Complexity

Conditions 12
Paths 442

Size

Total Lines 158
Code Lines 128

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 128
c 0
b 0
f 0
nc 442
nop 1
dl 0
loc 158
rs 2.86

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
//namespace empty
4
use Pagantis\ModuleUtils\Exception\OrderNotFoundException;
5
use Pagantis\OrdersApiClient\Model\Order\User\Address;
6
7
if (!defined('ABSPATH')) {
8
    exit;
9
}
10
11
define('__ROOT__', dirname(dirname(__FILE__)));
12
13
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...
14
{
15
    const METHOD_ID = "pagantis";
16
17
    /** Orders tablename */
18
    const ORDERS_TABLE = 'cart_process';
19
20
    /** Concurrency tablename */
21
    const LOGS_TABLE = 'pagantis_logs';
22
23
    const NOT_CONFIRMED = 'No se ha podido confirmar el pago';
24
25
    /**
26
     * WcPagantisGateway constructor.
27
     */
28
    public function __construct()
29
    {
30
        //Mandatory vars for plugin
31
        $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...
32
        $this->icon = esc_url(plugins_url('../assets/images/logo.png', __FILE__));
0 ignored issues
show
Bug introduced by
The function esc_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

32
        $this->icon = /** @scrutinizer ignore-call */ esc_url(plugins_url('../assets/images/logo.png', __FILE__));
Loading history...
Bug introduced by
The function plugins_url was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

32
        $this->icon = esc_url(/** @scrutinizer ignore-call */ plugins_url('../assets/images/logo.png', __FILE__));
Loading history...
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...
33
        $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...
34
35
        //Useful vars
36
        $this->template_path = plugin_dir_path(__FILE__) . '../templates/';
0 ignored issues
show
Bug Best Practice introduced by
The property template_path does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
Bug introduced by
The function plugin_dir_path was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

39
        $this->plugin_info = /** @scrutinizer ignore-call */ get_file_data($this->mainFileLocation, array('Version' => 'Version'), false);
Loading history...
40
41
        //Panel form fields
42
        $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...
43
        $this->init_settings();
44
45
        $this->settings['ok_url'] = (getenv('PAGANTIS_URL_OK')!='')?getenv('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...
46
        $this->settings['ko_url'] = (getenv('PAGANTIS_URL_KO')!='')?getenv('PAGANTIS_URL_KO'):$this->generateKoUrl();
47
        foreach ($this->settings as $setting_key => $setting_value) {
48
            $this->$setting_key = $setting_value;
49
        }
50
51
        //Hooks
52
        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

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

56
        /** @scrutinizer ignore-call */ add_filter('woocommerce_payment_complete_order_status', array($this,'pagantisCompleteStatus'), 10, 3);
Loading history...
57
        add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
58
    }
59
60
    /*
61
     * Replace 'textdomain' with your plugin's textdomain. e.g. 'woocommerce'.
62
     * File to be named, for example, yourtranslationfile-en_GB.mo
63
     * File to be placed, for example, wp-content/lanaguages/textdomain/yourtranslationfile-en_GB.mo
64
     */
65
    public function loadPagantisTranslation($mofile, $domain)
66
    {
67
        if ('pagantis' === $domain) {
68
            $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

68
            $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...
69
        }
70
        return $mofile;
71
    }
72
73
    /***********
74
     *
75
     * HOOKS
76
     *
77
     ***********/
78
79
    /**
80
     * PANEL - Display admin panel -> Hook: woocommerce_update_options_payment_gateways_pagantis
81
     */
82
    public function admin_options()
83
    {
84
        $template_fields = array(
85
            'panel_header' => $this->title,
86
            'panel_description' => $this->method_description,
87
            'button1_label' => __('Login to panel of ', 'pagantis') . ucfirst(WcPagantisGateway::METHOD_ID),
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

87
            'button1_label' => /** @scrutinizer ignore-call */ __('Login to panel of ', 'pagantis') . ucfirst(WcPagantisGateway::METHOD_ID),
Loading history...
88
            'button2_label' => __('Documentation', 'pagantis'),
89
            'logo' => $this->icon,
90
            'settings' => $this->generate_settings_html($this->form_fields, false)
91
        );
92
        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

92
        /** @scrutinizer ignore-call */ wc_get_template('admin_header.php', $template_fields, '', $this->template_path);
Loading history...
93
    }
94
95
    /**
96
     * PANEL - Check admin panel fields -> Hook: admin_notices
97
     */
98
    public function pagantisCheckFields()
99
    {
100
        $error_string = '';
101
        if ($this->settings['enabled'] !== 'yes') {
102
            return;
103
        } elseif (!version_compare(phpversion(), '5.3.0', '>=')) {
104
            $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

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

109
        } elseif (!in_array(/** @scrutinizer ignore-call */ get_woocommerce_currency(), $this->allowed_currencies)) {
Loading history...
110
            $error_string =  __(' only can be used in Euros', 'pagantis');
111
            $this->settings['enabled'] = 'no';
112
        } elseif (getenv('PAGANTIS_SIMULATOR_MAX_INSTALLMENTS')<'2'
113
                  || getenv('PAGANTIS_SIMULATOR_MAX_INSTALLMENTS')>'12') {
114
            $error_string = __(' only can be payed from 2 to 12 installments', 'pagantis');
115
        } elseif (getenv('PAGANTIS_SIMULATOR_START_INSTALLMENTS')<'2'
116
                  || getenv('PAGANTIS_SIMULATOR_START_INSTALLMENTS')>'12') {
117
            $error_string = __(' only can be payed from 2 to 12 installments', 'pagantis');
118
        } elseif (getenv('PAGANTIS_DISPLAY_MIN_AMOUNT')<0) {
119
            $error_string = __(' can not have a minimum amount less than 0', 'pagantis');
120
        }
121
122
        if ($error_string!='') {
123
            $template_fields = array(
124
                'error_msg' => ucfirst(WcPagantisGateway::METHOD_ID).' '.$error_string,
125
            );
126
            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

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

196
                $orderElement = /** @scrutinizer ignore-call */ wc_get_order($previousOrder);
Loading history...
197
                $orderCreated = $orderElement->get_date_created();
198
                $orderHistory
199
                    ->setAmount(intval(100 * $orderElement->get_total()))
200
                    ->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

200
                    ->setDate(/** @scrutinizer ignore-type */ new \DateTime($orderCreated->date('Y-m-d H:i:s')))
Loading history...
201
                ;
202
                $orderUser->addOrderHistory($orderHistory);
203
            }
204
205
            $details = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details();
206
            $shippingCost = $order->shipping_total;
207
            $details->setShippingCost(intval(strval(100 * $shippingCost)));
208
            $items = $woocommerce->cart->get_cart();
209
            foreach ($items as $key => $item) {
210
                $product = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product();
211
                $product
212
                    ->setAmount(intval(100 * $item['line_total']))
213
                    ->setQuantity($item['quantity'])
214
                    ->setDescription($item['data']->get_description());
215
                $details->addProduct($product);
216
            }
217
218
            $orderShoppingCart = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart();
219
            $orderShoppingCart
220
                ->setDetails($details)
221
                ->setOrderReference($order->get_id())
222
                ->setPromotedAmount(0)
223
                ->setTotalAmount(intval(strval(100 * $order->total)))
224
            ;
225
            $orderConfigurationUrls = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Urls();
226
            $cancelUrl = $this->getKoUrl($order);
227
            $callback_arg = array(
228
                'wc-api'=>'wcpagantisgateway',
229
                'key'=>$order->get_order_key(),
230
                'order-received'=>$order->get_id());
231
            $callback_url = add_query_arg($callback_arg, 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

231
            $callback_url = /** @scrutinizer ignore-call */ add_query_arg($callback_arg, 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

231
            $callback_url = add_query_arg($callback_arg, /** @scrutinizer ignore-call */ home_url('/'));
Loading history...
232
            $orderConfigurationUrls
233
                ->setCancel($cancelUrl)
234
                ->setKo($callback_url)
235
                ->setAuthorizedNotificationCallback($callback_url)
236
                ->setRejectedNotificationCallback($callback_url)
237
                ->setOk($callback_url)
238
            ;
239
            $orderChannel = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Channel();
240
            $orderChannel
241
                ->setAssistedSale(false)
242
                ->setType(\Pagantis\OrdersApiClient\Model\Order\Configuration\Channel::ONLINE)
243
            ;
244
            $orderConfiguration = new \Pagantis\OrdersApiClient\Model\Order\Configuration();
245
            $orderConfiguration
246
                ->setChannel($orderChannel)
247
                ->setUrls($orderConfigurationUrls)
248
            ;
249
            $metadataOrder = new \Pagantis\OrdersApiClient\Model\Order\Metadata();
250
            $metadata = array(
251
                'woocommerce' => 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

251
                'woocommerce' => /** @scrutinizer ignore-call */ WC()->version,
Loading history...
252
                'pagantis'         => $this->plugin_info['Version'],
253
                'php'         => phpversion()
254
            );
255
            foreach ($metadata as $key => $metadatum) {
256
                $metadataOrder->addMetadata($key, $metadatum);
257
            }
258
            $orderApiClient = new \Pagantis\OrdersApiClient\Model\Order();
259
            $orderApiClient
260
                ->setConfiguration($orderConfiguration)
261
                ->setMetadata($metadataOrder)
262
                ->setShoppingCart($orderShoppingCart)
263
                ->setUser($orderUser)
264
            ;
265
266
            if ($this->pagantis_public_key=='' || $this->pagantis_private_key=='') {
267
                throw new \Exception('Public and Secret Key not found');
268
            }
269
            $orderClient = new \Pagantis\OrdersApiClient\Client($this->pagantis_public_key, $this->pagantis_private_key);
270
            $pagantisOrder = $orderClient->createOrder($orderApiClient);
271
            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...
272
                $url = $pagantisOrder->getActionUrls()->getForm();
273
                $this->insertRow($order->get_id(), $pagantisOrder->getId());
274
            } else {
275
                throw new OrderNotFoundException();
276
            }
277
278
            if ($url=="") {
279
                throw new Exception(_("No ha sido posible obtener una respuesta de Pagantis"));
280
            } elseif (getenv('PAGANTIS_FORM_DISPLAY_TYPE')=='0') {
281
                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

281
                /** @scrutinizer ignore-call */ wp_redirect($url);
Loading history...
282
                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...
283
            } else {
284
                $template_fields = array(
285
                    'url' => $url,
286
                    'checkoutUrl'   => $cancelUrl
287
                );
288
                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

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

291
            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

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

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

292
            $checkout_url = /** @scrutinizer ignore-call */ get_permalink(wc_get_page_id('checkout'));
Loading history...
293
            wp_redirect($checkout_url);
294
            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...
295
        }
296
    }
297
298
    /**
299
     * NOTIFICATION - Endpoint for Json notification - Hook: woocommerce_api_wcpagantisgateway
300
     */
301
    public function pagantisNotification()
302
    {
303
        try {
304
            $origin = ($_SERVER['REQUEST_METHOD'] == 'POST') ? 'Notify' : 'Order';
305
306
            include_once('notifyController.php');
307
            $notify = new WcPagantisNotify();
308
            $notify->setOrigin($origin);
309
            /** @var \Pagantis\ModuleUtils\Model\Response\AbstractJsonResponse $result */
310
            $result = $notify->processInformation();
311
        } catch (Exception $exception) {
312
            $result['notification_message'] = $exception->getMessage();
313
            $result['notification_error'] = true;
314
        }
315
316
        $paymentOrder = new WC_Order($result->getMerchantOrderId());
317
        if ($paymentOrder instanceof WC_Order) {
318
            $orderStatus = strtolower($paymentOrder->get_status());
319
        } else {
320
            $orderStatus = 'cancelled';
321
        }
322
        $acceptedStatus = array('processing', 'completed');
323
        if (in_array($orderStatus, $acceptedStatus)) {
324
            $returnUrl = $this->getOkUrl($paymentOrder);
325
        } else {
326
            $returnUrl = $this->getKoUrl($paymentOrder);
327
        }
328
329
        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

329
        /** @scrutinizer ignore-call */ 
330
        wp_redirect($returnUrl);
Loading history...
330
        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...
331
    }
332
333
    /**
334
     * After failed status, set to processing not complete -> Hook: woocommerce_payment_complete_order_status
335
     * @param $status
336
     * @param $order_id
337
     * @param $order
338
     *
339
     * @return string
340
     */
341
    public function pagantisCompleteStatus($status, $order_id, $order)
342
    {
343
        if ($order->get_payment_method() == WcPagantisGateway::METHOD_ID) {
344
            if ($order->get_status() == 'failed') {
345
                $status = 'processing';
346
            } elseif ($order->get_status() == 'pending' && $status=='completed') {
347
                $status = 'processing';
348
            }
349
        }
350
351
        return $status;
352
    }
353
354
    /***********
355
     *
356
     * REDEFINED FUNCTIONS
357
     *
358
     ***********/
359
360
    /**
361
     * CHECKOUT - Check if payment method is available (called by woocommerce, can't apply cammel caps)
362
     * @return bool
363
     */
364
    public function is_available()
365
    {
366
        if ($this->enabled==='yes' && $this->pagantis_public_key!='' && $this->pagantis_private_key!='' &&
367
            $this->get_order_total()>getenv('PAGANTIS_DISPLAY_MIN_AMOUNT')) {
368
            return true;
369
        }
370
371
        return false;
372
    }
373
374
    /**
375
     * CHECKOUT - Get the checkout title (called by woocommerce, can't apply cammel caps)
376
     * @return string
377
     */
378
    public function get_title()
379
    {
380
        return ucfirst($this->id);
381
    }
382
383
    /**
384
     * CHECKOUT - Called after push pagantis button on checkout(called by woocommerce, can't apply cammel caps
385
     * @param $order_id
386
     * @return array
387
     */
388
    public function process_payment($order_id)
389
    {
390
        try {
391
            $order = new WC_Order($order_id);
392
393
            $redirectUrl = $order->get_checkout_payment_url(true); //pagantisReceiptPage function
394
            if (strpos($redirectUrl, 'order-pay=')===false) {
395
                $redirectUrl.= "&order-pay=".$order_id;
396
            }
397
398
            return array(
399
                'result'   => 'success',
400
                'redirect' => $redirectUrl
401
            );
402
403
        } catch (Exception $e) {
404
            wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

404
            /** @scrutinizer ignore-call */ wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
405
            return array();
406
        }
407
    }
408
409
    /**
410
     * CHECKOUT - simulator (called by woocommerce, can't apply cammel caps)
411
     */
412
    public function payment_fields()
413
    {
414
        $template_fields = array(
415
            'public_key' => $this->pagantis_public_key,
416
            '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

416
            'total' => /** @scrutinizer ignore-call */ WC()->session->cart_totals['total'],
Loading history...
417
            'enabled' =>  $this->settings['enabled'],
418
            'min_installments' => getenv('PAGANTIS_DISPLAY_MIN_AMOUNT'),
419
            'message' => __(getenv('PAGANTIS_TITLE_EXTRA'))
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

419
            'message' => /** @scrutinizer ignore-call */ __(getenv('PAGANTIS_TITLE_EXTRA'))
Loading history...
420
        );
421
        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

421
        /** @scrutinizer ignore-call */ 
422
        wc_get_template('checkout_description.php', $template_fields, '', $this->template_path);
Loading history...
422
    }
423
424
    /***********
425
     *
426
     * UTILS FUNCTIONS
427
     *
428
     ***********/
429
430
    /**
431
     * PANEL KO_URL FIELD
432
     * CHECKOUT PAGE => ?page_id=91 // ORDER-CONFIRMATION PAGE => ?page_id=91&order-pay=<order_id>&key=<order_key>
433
     */
434
    private function generateOkUrl()
435
    {
436
        return $this->generateUrl($this->get_return_url());
437
    }
438
439
    /**
440
     * PANEL OK_URL FIELD
441
     */
442
    private function generateKoUrl()
443
    {
444
        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

444
        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

444
        return $this->generateUrl(get_permalink(/** @scrutinizer ignore-call */ wc_get_page_id('checkout')));
Loading history...
445
    }
446
447
    /**
448
     * Replace empty space by {{var}}
449
     * @param $url
450
     *
451
     * @return string
452
     */
453
    private function generateUrl($url)
454
    {
455
        $parsed_url = parse_url($url);
456
        if ($parsed_url !== false) {
457
            $parsed_url['query'] = !isset($parsed_url['query']) ? '' : $parsed_url['query'];
458
            parse_str($parsed_url['query'], $arrayParams);
459
            foreach ($arrayParams as $keyParam => $valueParam) {
460
                if ($valueParam=='') {
461
                    $arrayParams[$keyParam] = '{{'.$keyParam.'}}';
462
                }
463
            }
464
            $parsed_url['query'] = http_build_query($arrayParams);
465
            $return_url = $this->unparseUrl($parsed_url);
466
            return urldecode($return_url);
467
        } else {
468
            return $url;
469
        }
470
    }
471
472
    /**
473
     * Replace {{}} by vars values inside ok_url
474
     * @param $order
475
     *
476
     * @return string
477
     */
478
    private function getOkUrl($order)
479
    {
480
        return $this->getKeysUrl($order, $this->ok_url);
481
    }
482
483
    /**
484
     * Replace {{}} by vars values inside ko_url
485
     * @param $order
486
     *
487
     * @return string
488
     */
489
    private function getKoUrl($order)
490
    {
491
        return $this->getKeysUrl($order, $this->ko_url);
492
    }
493
494
    /**
495
     * Replace {{}} by vars values
496
     * @param $order
497
     * @param $url
498
     *
499
     * @return string
500
     */
501
    private function getKeysUrl($order, $url)
502
    {
503
        $defaultFields = (get_class($order)=='WC_Order') ?
504
            array('order-received'=>$order->get_id(), 'key'=>$order->get_order_key()) :
505
            array();
506
507
        $parsedUrl = parse_url($url);
508
        if ($parsedUrl !== false) {
509
            //Replace parameters from url
510
            $parsedUrl['query'] = $this->getKeysParametersUrl($parsedUrl['query'], $defaultFields);
511
512
            //Replace path from url
513
            $parsedUrl['path'] = $this->getKeysPathUrl($parsedUrl['path'], $defaultFields);
514
515
            $returnUrl = $this->unparseUrl($parsedUrl);
516
            return $returnUrl;
517
        }
518
        return $url;
519
    }
520
521
    /**
522
     * Replace {{}} by vars values inside parameters
523
     * @param $queryString
524
     * @param $defaultFields
525
     *
526
     * @return string
527
     */
528
    private function getKeysParametersUrl($queryString, $defaultFields)
529
    {
530
        parse_str(html_entity_decode($queryString), $arrayParams);
531
        $commonKeys = array_intersect_key($arrayParams, $defaultFields);
532
        if (count($commonKeys)) {
533
            $arrayResult = array_merge($arrayParams, $defaultFields);
534
        } else {
535
            $arrayResult = $arrayParams;
536
        }
537
        return urldecode(http_build_query($arrayResult));
538
    }
539
540
    /**
541
     * Replace {{}} by vars values inside path
542
     * @param $pathString
543
     * @param $defaultFields
544
     *
545
     * @return string
546
     */
547
    private function getKeysPathUrl($pathString, $defaultFields)
548
    {
549
        $arrayParams = explode("/", $pathString);
550
        foreach ($arrayParams as $keyParam => $valueParam) {
551
            preg_match('#\{{.*?}\}#', $valueParam, $match);
552
            if (count($match)) {
553
                $key = str_replace(array('{{','}}'), array('',''), $match[0]);
554
                $arrayParams[$keyParam] = $defaultFields[$key];
555
            }
556
        }
557
        return implode('/', $arrayParams);
558
    }
559
560
    /**
561
     * Replace {{var}} by empty space
562
     * @param $parsed_url
563
     *
564
     * @return string
565
     */
566
    private function unparseUrl($parsed_url)
567
    {
568
        $scheme   = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
569
        $host     = isset($parsed_url['host']) ? $parsed_url['host'] : '';
570
        $port     = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
571
        $query    = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
572
        $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
573
        $path     = $parsed_url['path'];
574
        return $scheme . $host . $port . $path . $query . $fragment;
575
    }
576
577
    /**
578
     * Get the orders of a customer
579
     * @param $current_user
580
     * @param $billingEmail
581
     *
582
     * @return mixed
583
     */
584
    private function getOrders($current_user, $billingEmail)
585
    {
586
        $sign_up = '';
587
        $total_orders = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $total_orders is dead and can be removed.
Loading history...
588
        $total_amt = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $total_amt is dead and can be removed.
Loading history...
589
        $refund_amt = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $refund_amt is dead and can be removed.
Loading history...
590
        $total_refunds = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $total_refunds is dead and can be removed.
Loading history...
591
        $partial_refunds = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $partial_refunds is dead and can be removed.
Loading history...
592
        if ($current_user->user_login) {
593
            $is_guest = "false";
0 ignored issues
show
Unused Code introduced by
The assignment to $is_guest is dead and can be removed.
Loading history...
594
            $sign_up = substr($current_user->user_registered, 0, 10);
0 ignored issues
show
Unused Code introduced by
The assignment to $sign_up is dead and can be removed.
Loading history...
595
            $customer_orders = get_posts(array(
0 ignored issues
show
Bug introduced by
The function get_posts was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

595
            $customer_orders = /** @scrutinizer ignore-call */ get_posts(array(
Loading history...
596
                'numberposts' => - 1,
597
                'meta_key'    => '_customer_user',
598
                'meta_value'  => $current_user->ID,
599
                'post_type'   => array( 'shop_order' ),
600
                'post_status' => array( 'wc-completed', 'wc-processing', 'wc-refunded' ),
601
            ));
602
        } else {
603
            $is_guest = "true";
604
            $customer_orders = get_posts(array(
605
                'numberposts' => - 1,
606
                'meta_key'    => '_billing_email',
607
                'meta_value'  => $billingEmail,
608
                'post_type'   => array( 'shop_order' ),
609
                'post_status' => array( 'wc-completed', 'wc-processing', 'wc-refunded'),
610
            ));
611
            foreach ($customer_orders as $customer_order) {
612
                if (trim($sign_up)=='' ||
613
                    strtotime(substr($customer_order->post_date, 0, 10)) <= strtotime($sign_up)) {
614
                    $sign_up = substr($customer_order->post_date, 0, 10);
615
                }
616
            }
617
        }
618
619
        return $customer_orders;
620
    }
621
622
623
    /**
624
     * @param $orderId
625
     * @param $pagantisOrderId
626
     *
627
     * @throws Exception
628
     */
629
    private function insertRow($orderId, $pagantisOrderId)
630
    {
631
        global $wpdb;
632
        $this->checkDbTable();
633
        $tableName = $wpdb->prefix.self::ORDERS_TABLE;
634
635
        //Check if id exists
636
        $resultsSelect = $wpdb->get_results("select * from $tableName where id='$orderId'");
637
        $countResults = count($resultsSelect);
638
        if ($countResults == 0) {
639
            $wpdb->insert(
640
                $tableName,
641
                array('id' => $orderId, 'order_id' => $pagantisOrderId),
642
                array('%d', '%s')
643
            );
644
        } else {
645
            $wpdb->update(
646
                $tableName,
647
                array('order_id' => $pagantisOrderId),
648
                array('id' => $orderId),
649
                array('%s'),
650
                array('%d')
651
            );
652
        }
653
    }
654
655
    /**
656
     * Check if orders table exists
657
     */
658
    private function checkDbTable()
659
    {
660
        global $wpdb;
661
        $tableName = $wpdb->prefix.self::ORDERS_TABLE;
662
663
        if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName) {
664
            $charset_collate = $wpdb->get_charset_collate();
665
            $sql             = "CREATE TABLE $tableName ( id int, order_id varchar(50), wc_order_id varchar(50),  
666
                  UNIQUE KEY id (id)) $charset_collate";
667
668
            require_once(ABSPATH.'wp-admin/includes/upgrade.php');
0 ignored issues
show
Bug introduced by
The constant ABSPATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
669
            dbDelta($sql);
0 ignored issues
show
Bug introduced by
The function dbDelta was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

669
            /** @scrutinizer ignore-call */ dbDelta($sql);
Loading history...
670
        }
671
    }
672
}
673