Passed
Pull Request — master (#17)
by
unknown
02:06
created

WcPagantisGateway::payment_fields()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 10
rs 10
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
14
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...
15
{
16
    const METHOD_ID = "pagantis";
17
18
    /** Orders tablename */
19
    const ORDERS_TABLE = 'cart_process';
20
21
    /** Concurrency tablename */
22
    const LOGS_TABLE = 'pagantis_logs';
23
24
    const NOT_CONFIRMED = 'No se ha podido confirmar el pago';
25
26
    const CONFIG_TABLE = 'pagantis_config';
27
28
    /** @var Array $extraConfig */
29
    public $extraConfig;
30
31
    /**
32
     * WcPagantisGateway constructor.
33
     */
34
    public function __construct()
35
    {
36
        //Mandatory vars for plugin
37
        $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...
38
        $this->icon = esc_url(plugins_url('../assets/images/logo.png', __FILE__));
0 ignored issues
show
Bug introduced by
The function plugins_url was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

38
        $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...
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

38
        $this->icon = /** @scrutinizer ignore-call */ esc_url(plugins_url('../assets/images/logo.png', __FILE__));
Loading history...
39
        $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...
40
        $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...
41
        $this->title = $this->extraConfig['PAGANTIS_TITLE'];
0 ignored issues
show
Bug Best Practice introduced by
The property title does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
42
43
        //Useful vars
44
        $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

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

47
        $this->plugin_info = /** @scrutinizer ignore-call */ get_file_data($this->mainFileLocation, array('Version' => 'Version'), false);
Loading history...
48
49
        //Panel form fields
50
        $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...
51
        $this->init_settings();
52
53
        $this->extraConfig = $this->getExtraConfig();
54
55
        $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...
56
        $this->settings['ko_url'] = ($this->extraConfig['PAGANTIS_URL_KO']!='')?$this->extraConfig['PAGANTIS_URL_KO']:$this->generateKoUrl();
57
        foreach ($this->settings as $setting_key => $setting_value) {
58
            $this->$setting_key = $setting_value;
59
        }
60
61
        //Hooks
62
        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

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

66
        /** @scrutinizer ignore-call */ add_filter('woocommerce_payment_complete_order_status', array($this,'pagantisCompleteStatus'), 10, 3);
Loading history...
67
        add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
68
    }
69
70
    /**
71
     * @param $mofile
72
     * @param $domain
73
     *
74
     * @return string
75
     */
76
    public function loadPagantisTranslation($mofile, $domain)
77
    {
78
        if ('pagantis' === $domain) {
79
            $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

79
            $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...
80
        }
81
        return $mofile;
82
    }
83
84
    /***********
85
     *
86
     * HOOKS
87
     *
88
     ***********/
89
90
    /**
91
     * PANEL - Display admin panel -> Hook: woocommerce_update_options_payment_gateways_pagantis
92
     */
93
    public function admin_options()
94
    {
95
        $template_fields = array(
96
            'panel_header' => $this->title,
97
            'panel_description' => $this->method_description,
98
            '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

98
            'button1_label' => /** @scrutinizer ignore-call */ __('Login to panel of ', 'pagantis') . ucfirst(WcPagantisGateway::METHOD_ID),
Loading history...
99
            'button2_label' => __('Documentation', 'pagantis'),
100
            'logo' => $this->icon,
101
            'settings' => $this->generate_settings_html($this->form_fields, false)
102
        );
103
        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

103
        /** @scrutinizer ignore-call */ wc_get_template('admin_header.php', $template_fields, '', $this->template_path);
Loading history...
104
    }
105
106
    /**
107
     * PANEL - Check admin panel fields -> Hook: admin_notices
108
     */
109
    public function pagantisCheckFields()
110
    {
111
        $error_string = '';
112
        if ($this->settings['enabled'] !== 'yes') {
113
            return;
114
        } elseif (!version_compare(phpversion(), '5.3.0', '>=')) {
115
            $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

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

120
        } elseif (!in_array(/** @scrutinizer ignore-call */ get_woocommerce_currency(), $this->allowed_currencies)) {
Loading history...
121
            $error_string =  __(' only can be used in Euros', 'pagantis');
122
            $this->settings['enabled'] = 'no';
123
        } elseif ($this->extraConfig['PAGANTIS_SIMULATOR_MAX_INSTALLMENTS']<'2'
124
                  || $this->extraConfig['PAGANTIS_SIMULATOR_MAX_INSTALLMENTS']>'12') {
125
            $error_string = __(' only can be payed from 2 to 12 installments', 'pagantis');
126
        } elseif ($this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS']<'2'
127
                  || $this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS']>'12') {
128
            $error_string = __(' only can be payed from 2 to 12 installments', 'pagantis');
129
        } elseif ($this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT']<0) {
130
            $error_string = __(' can not have a minimum amount less than 0', 'pagantis');
131
        }
132
133
        if ($error_string!='') {
134
            $template_fields = array(
135
                'error_msg' => ucfirst(WcPagantisGateway::METHOD_ID).' '.$error_string,
136
            );
137
            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

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

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

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

244
            $callback_url = add_query_arg($callback_arg, /** @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

244
            $callback_url = /** @scrutinizer ignore-call */ add_query_arg($callback_arg, home_url('/'));
Loading history...
245
            $orderConfigurationUrls
246
                ->setCancel($cancelUrl)
247
                ->setKo($callback_url)
248
                ->setAuthorizedNotificationCallback($callback_url)
249
                ->setRejectedNotificationCallback($callback_url)
250
                ->setOk($callback_url)
251
            ;
252
            $orderChannel = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Channel();
253
            $orderChannel
254
                ->setAssistedSale(false)
255
                ->setType(\Pagantis\OrdersApiClient\Model\Order\Configuration\Channel::ONLINE)
256
            ;
257
            $orderConfiguration = new \Pagantis\OrdersApiClient\Model\Order\Configuration();
258
            $orderConfiguration
259
                ->setChannel($orderChannel)
260
                ->setUrls($orderConfigurationUrls)
261
            ;
262
            $metadataOrder = new \Pagantis\OrdersApiClient\Model\Order\Metadata();
263
            $metadata = array(
264
                '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

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

294
                /** @scrutinizer ignore-call */ wp_redirect($url);
Loading history...
295
                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...
296
            } else {
297
                $template_fields = array(
298
                    'url' => $url,
299
                    'checkoutUrl'   => $cancelUrl
300
                );
301
                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

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

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

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

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

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

342
        /** @scrutinizer ignore-call */ wp_redirect($returnUrl);
Loading history...
343
        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...
344
    }
345
346
    /**
347
     * After failed status, set to processing not complete -> Hook: woocommerce_payment_complete_order_status
348
     * @param $status
349
     * @param $order_id
350
     * @param $order
351
     *
352
     * @return string
353
     */
354
    public function pagantisCompleteStatus($status, $order_id, $order)
355
    {
356
        if ($order->get_payment_method() == WcPagantisGateway::METHOD_ID) {
357
            if ($order->get_status() == 'failed') {
358
                $status = 'processing';
359
            } elseif ($order->get_status() == 'pending' && $status=='completed') {
360
                $status = 'processing';
361
            }
362
        }
363
364
        return $status;
365
    }
366
367
    /***********
368
     *
369
     * REDEFINED FUNCTIONS
370
     *
371
     ***********/
372
373
    /**
374
     * CHECKOUT - Check if payment method is available (called by woocommerce, can't apply cammel caps)
375
     * @return bool
376
     */
377
    public function is_available()
378
    {
379
        if ($this->enabled==='yes' && $this->pagantis_public_key!='' && $this->pagantis_private_key!='' &&
380
            (int)$this->get_order_total()>$this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT']) {
381
            return true;
382
        }
383
384
        return false;
385
    }
386
387
    /**
388
     * CHECKOUT - Checkout + admin panel title(method_title - get_title) (called by woocommerce,can't apply cammel caps)
389
     * @return string
390
     */
391
    public function get_title()
392
    {
393
        return $this->extraConfig['PAGANTIS_TITLE'];
394
    }
395
396
    /**
397
     * CHECKOUT - Called after push pagantis button on checkout(called by woocommerce, can't apply cammel caps
398
     * @param $order_id
399
     * @return array
400
     */
401
    public function process_payment($order_id)
402
    {
403
        try {
404
            $order = new WC_Order($order_id);
405
406
            $redirectUrl = $order->get_checkout_payment_url(true); //pagantisReceiptPage function
407
            if (strpos($redirectUrl, 'order-pay=')===false) {
408
                $redirectUrl.="&order-pay=".$order_id;
409
            }
410
411
            return array(
412
                'result'   => 'success',
413
                'redirect' => $redirectUrl
414
            );
415
416
        } catch (Exception $e) {
417
            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

417
            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

417
            /** @scrutinizer ignore-call */ 
418
            wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
418
            return array();
419
        }
420
    }
421
422
    /**
423
     * CHECKOUT - simulator (called by woocommerce, can't apply cammel caps)
424
     */
425
    public function payment_fields()
426
    {
427
        $template_fields = array(
428
            'public_key' => $this->pagantis_public_key,
429
            '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

429
            'total' => /** @scrutinizer ignore-call */ WC()->session->cart_totals['total'],
Loading history...
430
            'enabled' =>  $this->settings['enabled'],
431
            'min_installments' => $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'],
432
            'message' => __($this->extraConfig['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

432
            'message' => /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE_EXTRA'])
Loading history...
433
        );
434
        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

434
        /** @scrutinizer ignore-call */ wc_get_template('checkout_description.php', $template_fields, '', $this->template_path);
Loading history...
435
    }
436
437
    /***********
438
     *
439
     * UTILS FUNCTIONS
440
     *
441
     ***********/
442
443
    /**
444
     * PANEL KO_URL FIELD
445
     * CHECKOUT PAGE => ?page_id=91 // ORDER-CONFIRMATION PAGE => ?page_id=91&order-pay=<order_id>&key=<order_key>
446
     */
447
    private function generateOkUrl()
448
    {
449
        return $this->generateUrl($this->get_return_url());
450
    }
451
452
    /**
453
     * PANEL OK_URL FIELD
454
     */
455
    private function generateKoUrl()
456
    {
457
        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

457
        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

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

608
            $customer_orders = /** @scrutinizer ignore-call */ get_posts(array(
Loading history...
609
                'numberposts' => - 1,
610
                'meta_key'    => '_customer_user',
611
                'meta_value'  => $current_user->ID,
612
                'post_type'   => array( 'shop_order' ),
613
                'post_status' => array( 'wc-completed', 'wc-processing', 'wc-refunded' ),
614
            ));
615
        } else {
616
            $is_guest = "true";
617
            $customer_orders = get_posts(array(
618
                'numberposts' => - 1,
619
                'meta_key'    => '_billing_email',
620
                'meta_value'  => $billingEmail,
621
                'post_type'   => array( 'shop_order' ),
622
                'post_status' => array( 'wc-completed', 'wc-processing', 'wc-refunded'),
623
            ));
624
            foreach ($customer_orders as $customer_order) {
625
                if (trim($sign_up)=='' ||
626
                    strtotime(substr($customer_order->post_date, 0, 10)) <= strtotime($sign_up)) {
627
                    $sign_up = substr($customer_order->post_date, 0, 10);
628
                }
629
            }
630
        }
631
632
        return $customer_orders;
633
    }
634
635
636
    /**
637
     * @param $orderId
638
     * @param $pagantisOrderId
639
     *
640
     * @throws Exception
641
     */
642
    private function insertRow($orderId, $pagantisOrderId)
643
    {
644
        global $wpdb;
645
        $this->checkDbTable();
646
        $tableName = $wpdb->prefix.self::ORDERS_TABLE;
647
648
        //Check if id exists
649
        $resultsSelect = $wpdb->get_results("select * from $tableName where id='$orderId'");
650
        $countResults = count($resultsSelect);
651
        if ($countResults == 0) {
652
            $wpdb->insert(
653
                $tableName,
654
                array('id' => $orderId, 'order_id' => $pagantisOrderId),
655
                array('%d', '%s')
656
            );
657
        } else {
658
            $wpdb->update(
659
                $tableName,
660
                array('order_id' => $pagantisOrderId),
661
                array('id' => $orderId),
662
                array('%s'),
663
                array('%d')
664
            );
665
        }
666
    }
667
668
    /**
669
     * Check if orders table exists
670
     */
671
    private function checkDbTable()
672
    {
673
        global $wpdb;
674
        $tableName = $wpdb->prefix.self::ORDERS_TABLE;
675
676
        if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName) {
677
            $charset_collate = $wpdb->get_charset_collate();
678
            $sql             = "CREATE TABLE $tableName ( id int, order_id varchar(50), wc_order_id varchar(50),  
679
                  UNIQUE KEY id (id)) $charset_collate";
680
681
            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...
682
            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

682
            /** @scrutinizer ignore-call */ dbDelta($sql);
Loading history...
683
        }
684
    }
685
686
    /**
687
     * @return array
688
     */
689
    private function getExtraConfig()
690
    {
691
        global $wpdb;
692
        $tableName = $wpdb->prefix.self::CONFIG_TABLE;
693
        $response = array();
694
        $dbResult = $wpdb->get_results("select config, value from $tableName", ARRAY_A);
0 ignored issues
show
Bug introduced by
The constant ARRAY_A was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
695
        foreach ($dbResult as $value) {
696
            $response[$value['config']] = $value['value'];
697
        }
698
699
        return $response;
700
    }
701
}
702