Passed
Pull Request — master (#18)
by
unknown
03:00
created

WcPagantisGateway::get_title()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
//namespace empty
4
use Pagantis\ModuleUtils\Exception\OrderNotFoundException;
5
use Pagantis\OrdersApiClient\Model\Order\User\Address;
6
use Pagantis\OrdersApiClient\Model\Order\User;
7
use Pagantis\OrdersApiClient\Model\Order\User\OrderHistory;
8
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details;
9
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart;
10
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product;
11
use Pagantis\OrdersApiClient\Model\Order\Metadata;
12
use Pagantis\OrdersApiClient\Model\Order\Configuration\Urls;
13
use Pagantis\OrdersApiClient\Model\Order\Configuration\Channel;
14
use Pagantis\OrdersApiClient\Model\Order\Configuration;
15
use Pagantis\OrdersApiClient\Client;
16
17
if (!defined('ABSPATH')) {
18
    exit;
19
}
20
21
define('__ROOT__', dirname(dirname(__FILE__)));
22
23
24
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...
25
{
26
    const METHOD_ID = "pagantis";
27
28
    /** Orders tablename */
29
    const ORDERS_TABLE = 'cart_process';
30
31
    /** Concurrency tablename */
32
    const LOGS_TABLE = 'pagantis_logs';
33
34
    const NOT_CONFIRMED = 'No se ha podido confirmar el pago';
35
36
    const CONFIG_TABLE = 'pagantis_config';
37
38
    /** @var Array $extraConfig */
39
    public $extraConfig;
40
41
    /**
42
     * WcPagantisGateway constructor.
43
     */
44
    public function __construct()
45
    {
46
        //Mandatory vars for plugin
47
        $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...
48
        $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

48
        $this->icon = /** @scrutinizer ignore-call */ esc_url(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 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

48
        $this->icon = esc_url(/** @scrutinizer ignore-call */ plugins_url('../assets/images/logo.png', __FILE__));
Loading history...
49
        $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...
50
        $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...
51
        $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...
52
53
        //Useful vars
54
        $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

54
        $this->template_path = /** @scrutinizer ignore-call */ plugin_dir_path(__FILE__) . '../templates/';
Loading history...
55
        $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...
56
        $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...
57
        $this->plugin_info = get_file_data($this->mainFileLocation, array('Version' => 'Version'), false);
0 ignored issues
show
Bug introduced by
The function get_file_data was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

57
        $this->plugin_info = /** @scrutinizer ignore-call */ get_file_data($this->mainFileLocation, array('Version' => 'Version'), false);
Loading history...
Bug Best Practice introduced by
The property plugin_info does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
58
59
        //Panel form fields
60
        $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...
61
        $this->init_settings();
62
63
        $this->extraConfig = $this->getExtraConfig();
64
65
        $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...
66
        $this->settings['ko_url'] = ($this->extraConfig['PAGANTIS_URL_KO']!='')?$this->extraConfig['PAGANTIS_URL_KO']:$this->generateKoUrl();
67
        foreach ($this->settings as $setting_key => $setting_value) {
68
            $this->$setting_key = $setting_value;
69
        }
70
71
        //Hooks
72
        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

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

76
        /** @scrutinizer ignore-call */ add_filter('woocommerce_payment_complete_order_status', array($this,'pagantisCompleteStatus'), 10, 3);
Loading history...
77
        add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
78
    }
79
80
    /**
81
     * @param $mofile
82
     * @param $domain
83
     *
84
     * @return string
85
     */
86
    public function loadPagantisTranslation($mofile, $domain)
87
    {
88
        if ('pagantis' === $domain) {
89
            $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

89
            $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...
90
        }
91
        return $mofile;
92
    }
93
94
    /***********
95
     *
96
     * HOOKS
97
     *
98
     ***********/
99
100
    /**
101
     * PANEL - Display admin panel -> Hook: woocommerce_update_options_payment_gateways_pagantis
102
     */
103
    public function admin_options()
104
    {
105
        $template_fields = array(
106
            'panel_header' => $this->title,
107
            'panel_description' => $this->method_description,
108
            '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

108
            'button1_label' => /** @scrutinizer ignore-call */ __('Login to panel of ', 'pagantis') . ucfirst(WcPagantisGateway::METHOD_ID),
Loading history...
109
            'button2_label' => __('Documentation', 'pagantis'),
110
            'logo' => $this->icon,
111
            'settings' => $this->generate_settings_html($this->form_fields, false)
112
        );
113
        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

113
        /** @scrutinizer ignore-call */ 
114
        wc_get_template('admin_header.php', $template_fields, '', $this->template_path);
Loading history...
114
    }
115
116
    /**
117
     * PANEL - Check admin panel fields -> Hook: admin_notices
118
     */
119
    public function pagantisCheckFields()
120
    {
121
        $error_string = '';
122
        if ($this->settings['enabled'] !== 'yes') {
123
            return;
124
        } elseif (!version_compare(phpversion(), '5.3.0', '>=')) {
125
            $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

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

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

147
            /** @scrutinizer ignore-call */ wc_get_template('error_msg.php', $template_fields, '', $this->template_path);
Loading history...
148
        }
149
    }
150
151
152
    /**
153
     * CHECKOUT - Generate the pagantis form. "Return" iframe or redirect. - Hook: woocommerce_receipt_pagantis
154
     * @param $order_id
155
     *
156
     * @throws Exception
157
     */
158
    public function pagantisReceiptPage($order_id)
159
    {
160
        try {
161
            require_once(__ROOT__.'/vendor/autoload.php');
162
            global $woocommerce;
163
            $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...
164
            $order->set_payment_method(ucfirst($this->id)); //Method showed in confirmation page.
165
            $order->save();
166
167
            if (!isset($order)) {
168
                throw new Exception(_("Order not found"));
169
            }
170
171
            $shippingAddress = $order->get_address('shipping');
172
            $billingAddress = $order->get_address('billing');
173
            if ($shippingAddress['address_1'] == '') {
174
                $shippingAddress = $billingAddress;
175
            }
176
177
            $national_id = $this->getNationalId($order);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $national_id is correct as $this->getNationalId($order) targeting WcPagantisGateway::getNationalId() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
178
            $tax_id = $this->getTaxId($order);
179
180
            $userAddress = new Address();
181
            $userAddress
182
                ->setZipCode($shippingAddress['postcode'])
183
                ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name'])
184
                ->setCountryCode('ES')
185
                ->setCity($shippingAddress['city'])
186
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
187
            ;
188
            $orderShippingAddress = new Address();
189
            $orderShippingAddress
190
                ->setZipCode($shippingAddress['postcode'])
191
                ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name'])
192
                ->setCountryCode('ES')
193
                ->setCity($shippingAddress['city'])
194
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
195
                ->setFixPhone($shippingAddress['phone'])
196
                ->setMobilePhone($shippingAddress['phone'])
197
                ->setNationalId($national_id)
198
                ->setTaxId($tax_id)
199
            ;
200
            $orderBillingAddress =  new Address();
201
            $orderBillingAddress
202
                ->setZipCode($billingAddress['postcode'])
203
                ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name'])
204
                ->setCountryCode('ES')
205
                ->setCity($billingAddress['city'])
206
                ->setAddress($billingAddress['address_1']." ".$billingAddress['address_2'])
207
                ->setFixPhone($billingAddress['phone'])
208
                ->setMobilePhone($billingAddress['phone'])
209
                ->setNationalId($national_id)
210
                ->setTaxId($tax_id)
211
            ;
212
            $orderUser = new User();
213
            $orderUser
214
                ->setAddress($userAddress)
215
                ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name'])
216
                ->setBillingAddress($orderBillingAddress)
217
                ->setEmail($billingAddress['email'])
218
                ->setFixPhone($billingAddress['phone'])
219
                ->setMobilePhone($billingAddress['phone'])
220
                ->setShippingAddress($orderShippingAddress)
221
                ->setNationalId($national_id)
222
                ->setTaxId($tax_id)
223
            ;
224
225
            $previousOrders = $this->getOrders($order->get_user(), $billingAddress['email']);
226
            foreach ($previousOrders as $previousOrder) {
227
                $orderHistory = new OrderHistory();
228
                $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

228
                $orderElement = /** @scrutinizer ignore-call */ wc_get_order($previousOrder);
Loading history...
229
                $orderCreated = $orderElement->get_date_created();
230
                $orderHistory
231
                    ->setAmount(intval(100 * $orderElement->get_total()))
232
                    ->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

232
                    ->setDate(/** @scrutinizer ignore-type */ new \DateTime($orderCreated->date('Y-m-d H:i:s')))
Loading history...
233
                ;
234
                $orderUser->addOrderHistory($orderHistory);
235
            }
236
237
            $details = new Details();
238
            $shippingCost = $order->shipping_total;
239
            $details->setShippingCost(intval(strval(100 * $shippingCost)));
240
            $items = $woocommerce->cart->get_cart();
241
            foreach ($items as $key => $item) {
242
                $product = new Product();
243
                $productDescription = sprintf(
244
                    '%s %s %s',
245
                    $item['data']->get_title(),
246
                    $item['data']->get_description(),
247
                    $item['data']->get_short_description()
248
                );
249
                $product
250
                    ->setAmount(intval(100 * $item['line_total']))
251
                    ->setQuantity($item['quantity'])
252
                    ->setDescription($productDescription);
253
                $details->addProduct($product);
254
            }
255
256
            $orderShoppingCart = new ShoppingCart();
257
            $orderShoppingCart
258
                ->setDetails($details)
259
                ->setOrderReference($order->get_id())
260
                ->setPromotedAmount(0)
261
                ->setTotalAmount(intval(strval(100 * $order->total)))
262
            ;
263
            $orderConfigurationUrls = new Urls();
264
            $cancelUrl = $this->getKoUrl($order);
265
            $callback_arg = array(
266
                'wc-api'=>'wcpagantisgateway',
267
                'key'=>$order->get_order_key(),
268
                'order-received'=>$order->get_id());
269
            $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

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

269
            $callback_url = /** @scrutinizer ignore-call */ add_query_arg($callback_arg, home_url('/'));
Loading history...
270
            $orderConfigurationUrls
271
                ->setCancel($cancelUrl)
272
                ->setKo($callback_url)
273
                ->setAuthorizedNotificationCallback($callback_url)
274
                ->setRejectedNotificationCallback($callback_url)
275
                ->setOk($callback_url)
276
            ;
277
            $orderChannel = new Channel();
278
            $orderChannel
279
                ->setAssistedSale(false)
280
                ->setType(Channel::ONLINE)
281
            ;
282
            $orderConfiguration = new Configuration();
283
            $language = strstr(get_locale(), '_', true);
0 ignored issues
show
Bug introduced by
The function get_locale was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

283
            $language = strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true);
Loading history...
284
            $orderConfiguration
285
                ->setChannel($orderChannel)
286
                ->setUrls($orderConfigurationUrls)
287
                ->setPurchaseCountry($language)
288
            ;
289
            $metadataOrder = new Metadata();
290
            $metadata = array(
291
                '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

291
                'woocommerce' => /** @scrutinizer ignore-call */ WC()->version,
Loading history...
292
                'pagantis'         => $this->plugin_info['Version'],
293
                'php'         => phpversion()
294
            );
295
            foreach ($metadata as $key => $metadatum) {
296
                $metadataOrder->addMetadata($key, $metadatum);
297
            }
298
            $orderApiClient = new Order();
0 ignored issues
show
Bug introduced by
The type 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...
299
            $orderApiClient
300
                ->setConfiguration($orderConfiguration)
301
                ->setMetadata($metadataOrder)
302
                ->setShoppingCart($orderShoppingCart)
303
                ->setUser($orderUser)
304
            ;
305
306
            if ($this->pagantis_public_key=='' || $this->pagantis_private_key=='') {
307
                throw new \Exception('Public and Secret Key not found');
308
            }
309
            $orderClient = new Client($this->pagantis_public_key, $this->pagantis_private_key);
310
            $pagantisOrder = $orderClient->createOrder($orderApiClient);
311
            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...
312
                $url = $pagantisOrder->getActionUrls()->getForm();
313
                $this->insertRow($order->get_id(), $pagantisOrder->getId());
314
            } else {
315
                throw new OrderNotFoundException();
316
            }
317
318
            if ($url=="") {
319
                throw new Exception(_("No ha sido posible obtener una respuesta de Pagantis"));
320
            } elseif ($this->extraConfig['PAGANTIS_FORM_DISPLAY_TYPE']=='0') {
321
                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

321
                /** @scrutinizer ignore-call */ wp_redirect($url);
Loading history...
322
                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...
323
            } else {
324
                $template_fields = array(
325
                    'url' => $url,
326
                    'checkoutUrl'   => $cancelUrl
327
                );
328
                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

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

331
            /** @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

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

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

332
            $checkout_url = /** @scrutinizer ignore-call */ get_permalink(wc_get_page_id('checkout'));
Loading history...
333
            wp_redirect($checkout_url);
334
            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...
335
        }
336
    }
337
338
    /**
339
     * NOTIFICATION - Endpoint for Json notification - Hook: woocommerce_api_wcpagantisgateway
340
     */
341
    public function pagantisNotification()
342
    {
343
        try {
344
            $origin = ($_SERVER['REQUEST_METHOD'] == 'POST') ? 'Notify' : 'Order';
345
346
            include_once('notifyController.php');
347
            $notify = new WcPagantisNotify();
348
            $notify->setOrigin($origin);
349
            /** @var \Pagantis\ModuleUtils\Model\Response\AbstractJsonResponse $result */
350
            $result = $notify->processInformation();
351
        } catch (Exception $exception) {
352
            $result['notification_message'] = $exception->getMessage();
353
            $result['notification_error'] = true;
354
        }
355
356
        $paymentOrder = new WC_Order($result->getMerchantOrderId());
357
        if ($paymentOrder instanceof WC_Order) {
358
            $orderStatus = strtolower($paymentOrder->get_status());
359
        } else {
360
            $orderStatus = 'cancelled';
361
        }
362
        $acceptedStatus = array('processing', 'completed');
363
        if (in_array($orderStatus, $acceptedStatus)) {
364
            $returnUrl = $this->getOkUrl($paymentOrder);
365
        } else {
366
            $returnUrl = $this->getKoUrl($paymentOrder);
367
        }
368
369
        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

369
        /** @scrutinizer ignore-call */ 
370
        wp_redirect($returnUrl);
Loading history...
370
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
371
    }
372
373
    /**
374
     * After failed status, set to processing not complete -> Hook: woocommerce_payment_complete_order_status
375
     * @param $status
376
     * @param $order_id
377
     * @param $order
378
     *
379
     * @return string
380
     */
381
    public function pagantisCompleteStatus($status, $order_id, $order)
382
    {
383
        if ($order->get_payment_method() == WcPagantisGateway::METHOD_ID) {
384
            if ($order->get_status() == 'failed') {
385
                $status = 'processing';
386
            } elseif ($order->get_status() == 'pending' && $status=='completed') {
387
                $status = 'processing';
388
            }
389
        }
390
391
        return $status;
392
    }
393
394
    /***********
395
     *
396
     * REDEFINED FUNCTIONS
397
     *
398
     ***********/
399
400
    /**
401
     * CHECKOUT - Check if payment method is available (called by woocommerce, can't apply cammel caps)
402
     * @return bool
403
     */
404
    public function is_available()
405
    {
406
        $locale = strtolower(strstr(get_locale(), '_', true));
0 ignored issues
show
Bug introduced by
The function get_locale was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

406
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
407
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
408
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
409
        if ($this->enabled==='yes' && $this->pagantis_public_key!='' && $this->pagantis_private_key!='' &&
410
            (int)$this->get_order_total()>$this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'] && $allowedCountry) {
411
            return true;
412
        }
413
414
        return false;
415
    }
416
417
    /**
418
     * CHECKOUT - Checkout + admin panel title(method_title - get_title) (called by woocommerce,can't apply cammel caps)
419
     * @return string
420
     */
421
    public function get_title()
422
    {
423
        return $this->extraConfig['PAGANTIS_TITLE'];
424
    }
425
426
    /**
427
     * CHECKOUT - Called after push pagantis button on checkout(called by woocommerce, can't apply cammel caps
428
     * @param $order_id
429
     * @return array
430
     */
431
    public function process_payment($order_id)
432
    {
433
        try {
434
            $order = new WC_Order($order_id);
435
436
            $redirectUrl = $order->get_checkout_payment_url(true); //pagantisReceiptPage function
437
            if (strpos($redirectUrl, 'order-pay=')===false) {
438
                $redirectUrl.="&order-pay=".$order_id;
439
            }
440
441
            return array(
442
                'result'   => 'success',
443
                'redirect' => $redirectUrl
444
            );
445
446
        } catch (Exception $e) {
447
            wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
0 ignored issues
show
Bug introduced by
The function wc_add_notice was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

447
            wc_add_notice(/** @scrutinizer ignore-call */ __('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
448
            return array();
449
        }
450
    }
451
452
    /**
453
     * CHECKOUT - simulator (called by woocommerce, can't apply cammel caps)
454
     */
455
    public function payment_fields()
456
    {
457
        $locale = strtolower(strstr(get_locale(), '_', true));
0 ignored issues
show
Bug introduced by
The function get_locale was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

457
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
458
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
459
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
460
461
        $template_fields = array(
462
            'public_key' => $this->pagantis_public_key,
463
            '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

463
            'total' => /** @scrutinizer ignore-call */ WC()->session->cart_totals['total'],
Loading history...
464
            'enabled' =>  $this->settings['enabled'],
465
            'min_installments' => $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'],
466
            '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

466
            'message' => /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE_EXTRA']),
Loading history...
467
            'simulator_enabled' => $this->settings['pagantis_simulator'],
468
            'locale' => $locale,
469
            'allowedCountry' => $allowedCountry,
470
            'simulator_type' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE']
471
        );
472
        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

472
        /** @scrutinizer ignore-call */ wc_get_template('checkout_description.php', $template_fields, '', $this->template_path);
Loading history...
473
    }
474
475
    /***********
476
     *
477
     * UTILS FUNCTIONS
478
     *
479
     ***********/
480
481
    /**
482
     * PANEL KO_URL FIELD
483
     * CHECKOUT PAGE => ?page_id=91 // ORDER-CONFIRMATION PAGE => ?page_id=91&order-pay=<order_id>&key=<order_key>
484
     */
485
    private function generateOkUrl()
486
    {
487
        return $this->generateUrl($this->get_return_url());
488
    }
489
490
    /**
491
     * PANEL OK_URL FIELD
492
     */
493
    private function generateKoUrl()
494
    {
495
        return $this->generateUrl(get_permalink(wc_get_page_id('checkout')));
0 ignored issues
show
Bug introduced by
The function wc_get_page_id was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

495
        return $this->generateUrl(/** @scrutinizer ignore-call */ get_permalink(wc_get_page_id('checkout')));
Loading history...
496
    }
497
498
    /**
499
     * Replace empty space by {{var}}
500
     * @param $url
501
     *
502
     * @return string
503
     */
504
    private function generateUrl($url)
505
    {
506
        $parsed_url = parse_url($url);
507
        if ($parsed_url !== false) {
508
            $parsed_url['query'] = !isset($parsed_url['query']) ? '' : $parsed_url['query'];
509
            parse_str($parsed_url['query'], $arrayParams);
510
            foreach ($arrayParams as $keyParam => $valueParam) {
511
                if ($valueParam=='') {
512
                    $arrayParams[$keyParam] = '{{'.$keyParam.'}}';
513
                }
514
            }
515
            $parsed_url['query'] = http_build_query($arrayParams);
516
            $return_url = $this->unparseUrl($parsed_url);
517
            return urldecode($return_url);
518
        } else {
519
            return $url;
520
        }
521
    }
522
523
    /**
524
     * Replace {{}} by vars values inside ok_url
525
     * @param $order
526
     *
527
     * @return string
528
     */
529
    private function getOkUrl($order)
530
    {
531
        return $this->getKeysUrl($order, $this->ok_url);
532
    }
533
534
    /**
535
     * Replace {{}} by vars values inside ko_url
536
     * @param $order
537
     *
538
     * @return string
539
     */
540
    private function getKoUrl($order)
541
    {
542
        return $this->getKeysUrl($order, $this->ko_url);
543
    }
544
545
    /**
546
     * Replace {{}} by vars values
547
     * @param $order
548
     * @param $url
549
     *
550
     * @return string
551
     */
552
    private function getKeysUrl($order, $url)
553
    {
554
        $defaultFields = (get_class($order)=='WC_Order') ?
555
            array('order-received'=>$order->get_id(), 'key'=>$order->get_order_key()) :
556
            array();
557
558
        $parsedUrl = parse_url($url);
559
        if ($parsedUrl !== false) {
560
            //Replace parameters from url
561
            $parsedUrl['query'] = $this->getKeysParametersUrl($parsedUrl['query'], $defaultFields);
562
563
            //Replace path from url
564
            $parsedUrl['path'] = $this->getKeysPathUrl($parsedUrl['path'], $defaultFields);
565
566
            $returnUrl = $this->unparseUrl($parsedUrl);
567
            return $returnUrl;
568
        }
569
        return $url;
570
    }
571
572
    /**
573
     * Replace {{}} by vars values inside parameters
574
     * @param $queryString
575
     * @param $defaultFields
576
     *
577
     * @return string
578
     */
579
    private function getKeysParametersUrl($queryString, $defaultFields)
580
    {
581
        parse_str(html_entity_decode($queryString), $arrayParams);
582
        $commonKeys = array_intersect_key($arrayParams, $defaultFields);
583
        if (count($commonKeys)) {
584
            $arrayResult = array_merge($arrayParams, $defaultFields);
585
        } else {
586
            $arrayResult = $arrayParams;
587
        }
588
        return urldecode(http_build_query($arrayResult));
589
    }
590
591
    /**
592
     * Replace {{}} by vars values inside path
593
     * @param $pathString
594
     * @param $defaultFields
595
     *
596
     * @return string
597
     */
598
    private function getKeysPathUrl($pathString, $defaultFields)
599
    {
600
        $arrayParams = explode("/", $pathString);
601
        foreach ($arrayParams as $keyParam => $valueParam) {
602
            preg_match('#\{{.*?}\}#', $valueParam, $match);
603
            if (count($match)) {
604
                $key = str_replace(array('{{','}}'), array('',''), $match[0]);
605
                $arrayParams[$keyParam] = $defaultFields[$key];
606
            }
607
        }
608
        return implode('/', $arrayParams);
609
    }
610
611
    /**
612
     * Replace {{var}} by empty space
613
     * @param $parsed_url
614
     *
615
     * @return string
616
     */
617
    private function unparseUrl($parsed_url)
618
    {
619
        $scheme   = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
620
        $host     = isset($parsed_url['host']) ? $parsed_url['host'] : '';
621
        $port     = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
622
        $query    = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
623
        $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
624
        $path     = $parsed_url['path'];
625
        return $scheme . $host . $port . $path . $query . $fragment;
626
    }
627
628
    /**
629
     * Get the orders of a customer
630
     * @param $current_user
631
     * @param $billingEmail
632
     *
633
     * @return mixed
634
     */
635
    private function getOrders($current_user, $billingEmail)
636
    {
637
        $sign_up = '';
638
        $total_orders = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $total_orders is dead and can be removed.
Loading history...
639
        $total_amt = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $total_amt is dead and can be removed.
Loading history...
640
        $refund_amt = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $refund_amt is dead and can be removed.
Loading history...
641
        $total_refunds = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $total_refunds is dead and can be removed.
Loading history...
642
        $partial_refunds = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $partial_refunds is dead and can be removed.
Loading history...
643
        if ($current_user->user_login) {
644
            $is_guest = "false";
0 ignored issues
show
Unused Code introduced by
The assignment to $is_guest is dead and can be removed.
Loading history...
645
            $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...
646
            $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

646
            $customer_orders = /** @scrutinizer ignore-call */ get_posts(array(
Loading history...
647
                'numberposts' => - 1,
648
                'meta_key'    => '_customer_user',
649
                'meta_value'  => $current_user->ID,
650
                'post_type'   => array( 'shop_order' ),
651
                'post_status' => array( 'wc-completed', 'wc-processing', 'wc-refunded' ),
652
            ));
653
        } else {
654
            $is_guest = "true";
655
            $customer_orders = get_posts(array(
656
                'numberposts' => - 1,
657
                'meta_key'    => '_billing_email',
658
                'meta_value'  => $billingEmail,
659
                'post_type'   => array( 'shop_order' ),
660
                'post_status' => array( 'wc-completed', 'wc-processing', 'wc-refunded'),
661
            ));
662
            foreach ($customer_orders as $customer_order) {
663
                if (trim($sign_up)=='' ||
664
                    strtotime(substr($customer_order->post_date, 0, 10)) <= strtotime($sign_up)) {
665
                    $sign_up = substr($customer_order->post_date, 0, 10);
666
                }
667
            }
668
        }
669
670
        return $customer_orders;
671
    }
672
673
674
    /**
675
     * @param $orderId
676
     * @param $pagantisOrderId
677
     *
678
     * @throws Exception
679
     */
680
    private function insertRow($orderId, $pagantisOrderId)
681
    {
682
        global $wpdb;
683
        $this->checkDbTable();
684
        $tableName = $wpdb->prefix.self::ORDERS_TABLE;
685
686
        //Check if id exists
687
        $resultsSelect = $wpdb->get_results("select * from $tableName where id='$orderId'");
688
        $countResults = count($resultsSelect);
689
        if ($countResults == 0) {
690
            $wpdb->insert(
691
                $tableName,
692
                array('id' => $orderId, 'order_id' => $pagantisOrderId),
693
                array('%d', '%s')
694
            );
695
        } else {
696
            $wpdb->update(
697
                $tableName,
698
                array('order_id' => $pagantisOrderId),
699
                array('id' => $orderId),
700
                array('%s'),
701
                array('%d')
702
            );
703
        }
704
    }
705
706
    /**
707
     * Check if orders table exists
708
     */
709
    private function checkDbTable()
710
    {
711
        global $wpdb;
712
        $tableName = $wpdb->prefix.self::ORDERS_TABLE;
713
714
        if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName) {
715
            $charset_collate = $wpdb->get_charset_collate();
716
            $sql             = "CREATE TABLE $tableName ( id int, order_id varchar(50), wc_order_id varchar(50),  
717
                  UNIQUE KEY id (id)) $charset_collate";
718
719
            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...
720
            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

720
            /** @scrutinizer ignore-call */ dbDelta($sql);
Loading history...
721
        }
722
    }
723
724
    /**
725
     * @return array
726
     */
727
    private function getExtraConfig()
728
    {
729
        global $wpdb;
730
        $tableName = $wpdb->prefix.self::CONFIG_TABLE;
731
        $response = array();
732
        $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...
733
        foreach ($dbResult as $value) {
734
            $response[$value['config']] = $value['value'];
735
        }
736
737
        return $response;
738
    }
739
740
    /**
741
     * @param $order
742
     *
743
     * @return null
744
     */
745
    private function getNationalId($order)
746
    {
747
        foreach ((array)$order->get_meta_data() as $mdObject) {
748
            $data = $mdObject->get_data();
749
            if ($data['key'] == 'vat_number') {
750
                return $data['value'];
751
            }
752
        }
753
754
        return null;
755
    }
756
757
    /**
758
     * @param $order
759
     *
760
     * @return mixed
761
     */
762
    private function getTaxId($order)
763
    {
764
        foreach ((array)$order->get_meta_data() as $mdObject) {
765
            $data = $mdObject->get_data();
766
            if ($data['key'] == 'billing_cfpiva') {
767
                return $data['value'];
768
            }
769
        }
770
    }
771
}
772