Passed
Pull Request — master (#9)
by
unknown
01:50
created

WcPaylaterGateway::insertRow()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 22
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 17
c 0
b 0
f 0
dl 0
loc 22
rs 9.7
cc 2
nc 2
nop 2
1
<?php
2
3
//namespace empty
4
use PagaMasTarde\OrdersApiClient\Model\Order\User\Address;
5
use PagaMasTarde\ModuleUtils\Exception\OrderNotFoundException;
6
7
if (!defined('ABSPATH')) {
8
    exit;
9
}
10
11
define('__ROOT__', dirname(dirname(__FILE__)));
12
13
class WcPaylaterGateway extends WC_Payment_Gateway
0 ignored issues
show
Bug introduced by
The type WC_Payment_Gateway was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
14
{
15
    const METHOD_ID             = "paylater";
16
    const METHOD_TITLE          = "Paga Más Tarde";
17
    const METHOD_ABREV          = "Paga+Tarde";
18
    const PAGA_MAS_TARDE        = 'pagamastarde';
19
    const PAYLATER_SHOPPER_URL  = 'https://shopper.pagamastarde.com/woocommerce/';
20
21
    /** Orders tablename */
22
    const ORDERS_TABLE = 'cart_process';
23
24
    /** Concurrency tablename */
25
    const LOGS_TABLE = 'pmt_logs';
26
27
    const NOT_CONFIRMED = 'No se ha podido confirmar el pago';
28
29
    /**
30
     * WcPaylaterGateway constructor.
31
     */
32
    public function __construct()
33
    {
34
        //Mandatory vars for plugin
35
        $this->id = WcPaylaterGateway::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...
36
        $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

36
        $this->icon = esc_url(/** @scrutinizer ignore-call */ plugins_url('../assets/images/logo.png', __FILE__));
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

36
        $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...
37
        $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...
38
        $this->method_title = WcPaylaterGateway::METHOD_TITLE;
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...
39
        $this->title = WcPaylaterGateway::METHOD_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...
40
41
        //Useful vars
42
        $this->template_path = plugin_dir_path(__FILE__) . '../templates/';
0 ignored issues
show
Bug introduced by
The function plugin_dir_path was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

42
        $this->template_path = /** @scrutinizer ignore-call */ plugin_dir_path(__FILE__) . '../templates/';
Loading history...
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...
43
        $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...
44
        $this->allowed_languages  = array("es_ES");
0 ignored issues
show
Bug Best Practice introduced by
The property allowed_languages does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
45
        $this->mainFileLocation = dirname(plugin_dir_path(__FILE__)) . '/WC_Paylater.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...
46
        $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

46
        $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...
47
48
        //Panel form fields
49
        $this->form_fields = include(plugin_dir_path(__FILE__).'../includes/settings-paylater.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...
50
        $this->init_settings();
51
52
        $this->settings['ok_url'] = (getenv('PMT_URL_OK')!='')?getenv('PMT_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...
53
        $this->settings['ko_url'] = (getenv('PMT_URL_KO')!='')?getenv('PMT_URL_KO'):$this->generateKoUrl();
54
        foreach ($this->settings as $setting_key => $setting_value) {
55
            $this->$setting_key = $setting_value;
56
        }
57
58
        //Hooks
59
        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

59
        /** @scrutinizer ignore-call */ add_action('woocommerce_update_options_payment_gateways_'.$this->id, array($this,'process_admin_options')); //Save plugin options
Loading history...
60
        add_action('admin_notices', array($this, 'paylaterCheckFields'));                          //Check config fields
61
        add_action('woocommerce_receipt_'.$this->id, array($this, 'paylaterReceiptPage'));          //Pmt form
62
        add_action('woocommerce_api_wcpaylatergateway', array($this, 'paylaterNotification'));      //Json Notification
63
        add_filter('woocommerce_payment_complete_order_status', array($this,'paylaterCompleteStatus'), 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

63
        /** @scrutinizer ignore-call */ add_filter('woocommerce_payment_complete_order_status', array($this,'paylaterCompleteStatus'), 10, 3);
Loading history...
64
    }
65
66
    /***********
67
     *
68
     * HOOKS
69
     *
70
     ***********/
71
72
    /**
73
     * PANEL - Display admin panel -> Hook: woocommerce_update_options_payment_gateways_paylater
74
     */
75
    public function admin_options()
76
    {
77
        $template_fields = array(
78
            'panel_header' => $this->title,
79
            'panel_description' => $this->method_description,
80
            'button1_label' => __('Login al panel de ', 'paylater') . WcPaylaterGateway::METHOD_TITLE,
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

80
            'button1_label' => /** @scrutinizer ignore-call */ __('Login al panel de ', 'paylater') . WcPaylaterGateway::METHOD_TITLE,
Loading history...
81
            'button2_label' => __('Documentación', 'paylater'),
82
            'logo' => $this->icon,
83
            'settings' => $this->generate_settings_html($this->form_fields, false)
84
        );
85
        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

85
        /** @scrutinizer ignore-call */ 
86
        wc_get_template('admin_header.php', $template_fields, '', $this->template_path);
Loading history...
86
    }
87
88
    /**
89
     * PANEL - Check admin panel fields -> Hook: admin_notices
90
     */
91
    public function paylaterCheckFields()
92
    {
93
        $error_string = '';
94
        if ($this->settings['enabled'] !== 'yes') {
95
            return;
96
        } elseif (!version_compare(phpversion(), '5.3.0', '>=')) {
97
            $error_string =  __(' no es compatible con su versión de php y/o curl', 'paylater');
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

97
            $error_string =  /** @scrutinizer ignore-call */ __(' no es compatible con su versión de php y/o curl', 'paylater');
Loading history...
98
            $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...
99
        } elseif ($this->settings['pmt_public_key']=="" || $this->settings['pmt_private_key']=="") {
100
            $keys_error =  <<<EOD
101
no está configurado correctamente, los campos Public Key y Secret Key son obligatorios para su funcionamiento
102
EOD;
103
            $error_string = __($keys_error, 'paylater');
104
            $this->settings['enabled'] = 'no';
105
        } 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

105
        } elseif (!in_array(/** @scrutinizer ignore-call */ get_woocommerce_currency(), $this->allowed_currencies)) {
Loading history...
106
            $error_string =  __(' solo puede ser usado en Euros', 'paylater');
107
            $this->settings['enabled'] = 'no';
108
        } elseif (!in_array(get_locale(), $this->allowed_languages)) {
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

108
        } elseif (!in_array(/** @scrutinizer ignore-call */ get_locale(), $this->allowed_languages)) {
Loading history...
109
            $error_string = __(' solo puede ser usado en Español', 'paylater');
110
            $this->settings['enabled'] = 'no';
111
        } elseif (getenv('PMT_SIMULATOR_MAX_INSTALLMENTS')<'2'
112
                  || getenv('PMT_SIMULATOR_MAX_INSTALLMENTS')>'12') {
113
            $error_string = __(' solo puede ser pagado de 2 a 12 plazos.', 'paylater');
114
        } elseif (getenv('PMT_SIMULATOR_START_INSTALLMENTS')<'2'
115
                  || getenv('PMT_SIMULATOR_START_INSTALLMENTS')>'12') {
116
            $error_string = __(' solo puede ser pagado de 2 a 12 plazos.', 'paylater');
117
        } elseif (getenv('PMT_DISPLAY_MIN_AMOUNT')<0) {
118
            $error_string = __(' el importe debe ser mayor a 0.', 'paylater');
119
        }
120
121
        if ($error_string!='') {
122
            $template_fields = array(
123
                'error_msg' => WcPaylaterGateway::METHOD_TITLE .' '.$error_string,
124
            );
125
            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

125
            /** @scrutinizer ignore-call */ wc_get_template('error_msg.php', $template_fields, '', $this->template_path);
Loading history...
126
        }
127
    }
128
129
130
    /**
131
     * CHECKOUT - Generate the pmt form. "Return" iframe or redirect. - Hook: woocommerce_receipt_paylater
132
     * @param $order_id
133
     *
134
     * @throws Exception
135
     */
136
    public function paylaterReceiptPage($order_id)
137
    {
138
        try {
139
            require_once(__ROOT__.'/vendor/autoload.php');
140
            global $woocommerce;
141
            $order = new WC_Order($order_id);
0 ignored issues
show
Bug introduced by
The type WC_Order was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
142
143
            if (!isset($order)) {
144
                throw new Exception(_("Order not found"));
145
            }
146
147
            $shippingAddress = $order->get_address('shipping');
148
            $billingAddress = $order->get_address('billing');
149
            if ($shippingAddress['address_1'] == '') {
150
                $shippingAddress = $billingAddress;
151
            }
152
153
            $userAddress = new Address();
154
            $userAddress
155
                ->setZipCode($shippingAddress['postcode'])
156
                ->setFullName($shippingAddress['fist_name']." ".$shippingAddress['last_name'])
157
                ->setCountryCode('ES')
158
                ->setCity($shippingAddress['city'])
159
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
160
            ;
161
            $orderShippingAddress = new Address();
162
            $orderShippingAddress
163
                ->setZipCode($shippingAddress['postcode'])
164
                ->setFullName($shippingAddress['fist_name']." ".$shippingAddress['last_name'])
165
                ->setCountryCode('ES')
166
                ->setCity($shippingAddress['city'])
167
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
168
                ->setFixPhone($shippingAddress['phone'])
169
                ->setMobilePhone($shippingAddress['phone'])
170
            ;
171
            $orderBillingAddress =  new Address();
172
            $orderBillingAddress
173
                ->setZipCode($billingAddress['postcode'])
174
                ->setFullName($billingAddress['fist_name']." ".$billingAddress['last_name'])
175
                ->setCountryCode('ES')
176
                ->setCity($billingAddress['city'])
177
                ->setAddress($billingAddress['address_1']." ".$billingAddress['address_2'])
178
                ->setFixPhone($billingAddress['phone'])
179
                ->setMobilePhone($billingAddress['phone'])
180
            ;
181
            $orderUser = new \PagaMasTarde\OrdersApiClient\Model\Order\User();
182
            $orderUser
183
                ->setAddress($userAddress)
184
                ->setFullName($billingAddress['fist_name']." ".$billingAddress['last_name'])
185
                ->setBillingAddress($orderBillingAddress)
186
                ->setEmail($billingAddress['email'])
187
                ->setFixPhone($billingAddress['phone'])
188
                ->setMobilePhone($billingAddress['phone'])
189
                ->setShippingAddress($orderShippingAddress)
190
            ;
191
192
            $previousOrders = $this->getOrders($order->get_user(), $billingAddress['email']);
193
            foreach ($previousOrders as $previousOrder) {
194
                $orderHistory = new \PagaMasTarde\OrdersApiClient\Model\Order\User\OrderHistory();
195
                $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

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

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

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

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

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

280
                /** @scrutinizer ignore-call */ wp_redirect($url);
Loading history...
281
                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...
282
            } else {
283
                $template_fields = array(
284
                    'css' => 'https://shopper.pagamastarde.com/css/paylater-modal.min.css',
285
                    'prestashopCss' => 'https://shopper.pagamastarde.com/css/paylater-prestashop.min.css',
286
                    'url' => $url,
287
                    'spinner' => esc_url(plugins_url('../assets/images/spinner.gif', __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

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

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

287
                    'spinner' => esc_url(/** @scrutinizer ignore-call */ plugins_url('../assets/images/spinner.gif', __FILE__)),
Loading history...
288
                    'checkoutUrl'   => $cancelUrl
289
                );
290
                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

290
                /** @scrutinizer ignore-call */ wc_get_template('iframe.php', $template_fields, '', $this->template_path);
Loading history...
291
            }
292
        } catch (\Exception $exception) {
293
            wc_add_notice(__('Error en el pago - ', 'paylater') . $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

293
            /** @scrutinizer ignore-call */ 
294
            wc_add_notice(__('Error en el pago - ', 'paylater') . $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

293
            wc_add_notice(/** @scrutinizer ignore-call */ __('Error en el pago - ', 'paylater') . $exception->getMessage(), 'error');
Loading history...
294
            $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

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

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

331
        /** @scrutinizer ignore-call */ 
332
        wp_redirect($returnUrl);
Loading history...
332
        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...
333
    }
334
335
    /**
336
     * After failed status, set to processing not complete -> Hook: woocommerce_payment_complete_order_status
337
     * @param $status
338
     * @param $order_id
339
     * @param $order
340
     *
341
     * @return string
342
     */
343
    public function paylaterCompleteStatus($status, $order_id, $order)
344
    {
345
        if ($order->get_payment_method() == WcPaylaterGateway::METHOD_ID) {
346
            if ($order->get_status() == 'failed') {
347
                $status = 'processing';
348
            } elseif ($order->get_status() == 'pending' && $status=='completed') {
349
                $status = 'processing';
350
            }
351
        }
352
353
        return $status;
354
    }
355
356
    /***********
357
     *
358
     * REDEFINED FUNCTIONS
359
     *
360
     ***********/
361
362
    /**
363
     * CHECKOUT - Check if payment method is available (called by woocommerce, can't apply cammel caps)
364
     * @return bool
365
     */
366
    public function is_available()
367
    {
368
        if ($this->enabled==='yes' && $this->pmt_public_key!='' && $this->pmt_private_key!='' &&
369
            $this->get_order_total()>getenv('PMT_DISPLAY_MIN_AMOUNT')) {
370
            return true;
371
        }
372
373
        return false;
374
    }
375
376
    /**
377
     * CHECKOUT - Get the checkout title (called by woocommerce, can't apply cammel caps)
378
     * @return string
379
     */
380
    public function get_title()
381
    {
382
        return getenv('PMT_TITLE');
383
    }
384
385
    /**
386
     * CHECKOUT - Called after push pmt button on checkout(called by woocommerce, can't apply cammel caps
387
     * @param $order_id
388
     * @return array
389
     */
390
    public function process_payment($order_id)
391
    {
392
        try {
393
            $order = new WC_Order($order_id);
394
395
            $redirectUrl = $order->get_checkout_payment_url(true); //paylaterReceiptPage function
396
            if (strpos($redirectUrl, 'order-pay=')===false) {
397
                $redirectUrl = "&order-pay=".$order->getId();
398
            }
399
400
            return array(
401
                'result'   => 'success',
402
                'redirect' => $redirectUrl
403
            );
404
405
        } catch (Exception $e) {
406
            wc_add_notice(__('Error en el pago ', 'paylater') . $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

406
            wc_add_notice(/** @scrutinizer ignore-call */ __('Error en el pago ', 'paylater') . $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

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

418
            'total' => /** @scrutinizer ignore-call */ WC()->session->cart_totals['total'],
Loading history...
419
            'enabled' =>  $this->settings['enabled'],
420
            'min_installments' => getenv('PMT_DISPLAY_MIN_AMOUNT'),
421
            'message' => getenv('PMT_TITLE_EXTRA')
422
        );
423
        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

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

446
        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

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

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

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