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

WcPagantis::pagantisRowMeta()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 7
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 12
rs 10
1
<?php
2
/**
3
 * Plugin Name: Pagantis
4
 * Plugin URI: http://www.pagantis.com/
5
 * Description: Financiar con Pagantis
6
 * Version: 8.0.0
7
 * Author: Pagantis
8
 */
9
10
//namespace Gateways;
11
12
13
if (!defined('ABSPATH')) {
14
    exit;
15
}
16
17
class WcPagantis
18
{
19
    const GIT_HUB_URL = 'https://github.com/pagantis/woocommerce';
20
    const PAGANTIS_DOC_URL = 'https://developer.pagamastarde.com';
21
    const SUPPORT_EML = 'mailto:[email protected]?Subject=woocommerce_plugin';
22
    /** Concurrency tablename */
23
    const LOGS_TABLE = 'pagantis_logs';
24
    /** Config tablename */
25
    const CONFIG_TABLE = 'pagantis_config';
26
27
    public $defaultConfigs = array('PAGANTIS_TITLE'=>'Instant Financing',
28
                            'PAGANTIS_SIMULATOR_DISPLAY_TYPE'=>'pmtSDK.simulator.types.SIMPLE',
29
                            'PAGANTIS_SIMULATOR_DISPLAY_SKIN'=>'pmtSDK.simulator.skins.BLUE',
30
                            'PAGANTIS_SIMULATOR_DISPLAY_POSITION'=>'hookDisplayProductButtons',
31
                            'PAGANTIS_SIMULATOR_START_INSTALLMENTS'=>3,
32
                            'PAGANTIS_SIMULATOR_MAX_INSTALLMENTS'=>12,
33
                            'PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'=>'default',
34
                            'PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION'=>'pmtSDK.simulator.positions.INNER',
35
                            'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'=>'default',
36
                            'PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'=>'default',
37
                            'PAGANTIS_FORM_DISPLAY_TYPE'=>0,
38
                            'PAGANTIS_DISPLAY_MIN_AMOUNT'=>1,
39
                            'PAGANTIS_URL_OK'=>'',
40
                            'PAGANTIS_URL_KO'=>'',
41
                            'PAGANTIS_TITLE_EXTRA' => 'Pay up to 12 comfortable installments with Pagantis. Completely online and sympathetic request, and the answer is immediate!'
42
    );
43
44
    /**
45
     * WC_Pagantis constructor.
46
     */
47
    public function __construct()
48
    {
49
        require_once(plugin_dir_path(__FILE__).'/vendor/autoload.php');
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

49
        require_once(/** @scrutinizer ignore-call */ plugin_dir_path(__FILE__).'/vendor/autoload.php');
Loading history...
50
51
        $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...
52
53
        $this->pagantisActivation();
54
55
        load_plugin_textdomain('pagantis', false, basename(dirname(__FILE__)).'/languages');
0 ignored issues
show
Bug introduced by
The function load_plugin_textdomain 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

55
        /** @scrutinizer ignore-call */ 
56
        load_plugin_textdomain('pagantis', false, basename(dirname(__FILE__)).'/languages');
Loading history...
56
        add_filter('woocommerce_payment_gateways', array($this, 'addPagantisGateway'));
0 ignored issues
show
Bug introduced by
The function add_filter was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

56
        /** @scrutinizer ignore-call */ 
57
        add_filter('woocommerce_payment_gateways', array($this, 'addPagantisGateway'));
Loading history...
57
        add_filter('woocommerce_available_payment_gateways', array($this, 'pagantisFilterGateways'), 9999);
58
        add_filter('plugin_row_meta', array($this, 'pagantisRowMeta'), 10, 2);
59
        add_filter('plugin_action_links_'.plugin_basename(__FILE__), array($this, 'pagantisActionLinks'));
0 ignored issues
show
Bug introduced by
The function plugin_basename 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
        add_filter('plugin_action_links_'./** @scrutinizer ignore-call */ plugin_basename(__FILE__), array($this, 'pagantisActionLinks'));
Loading history...
60
        add_action('woocommerce_after_add_to_cart_form', array($this, 'pagantisAddProductSimulator'));
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

60
        /** @scrutinizer ignore-call */ 
61
        add_action('woocommerce_after_add_to_cart_form', array($this, 'pagantisAddProductSimulator'));
Loading history...
61
        add_action('wp_enqueue_scripts', 'add_widget_js');
62
        add_action('rest_api_init', array($this, 'pagantisRegisterEndpoint')); //Endpoint
63
        add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
64
    }
65
66
    /*
67
     * Replace 'textdomain' with your plugin's textdomain. e.g. 'woocommerce'.
68
     * File to be named, for example, yourtranslationfile-en_GB.mo
69
     * File to be placed, for example, wp-content/lanaguages/textdomain/yourtranslationfile-en_GB.mo
70
     */
71
    public function loadPagantisTranslation($mofile, $domain)
72
    {
73
        if ('pagantis' === $domain) {
74
            $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

74
            $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...
75
        }
76
        return $mofile;
77
    }
78
79
    /**
80
     * Sql table
81
     */
82
    public function pagantisActivation()
83
    {
84
        global $wpdb;
85
        $tableName = $wpdb->prefix.self::CONFIG_TABLE;
86
87
        //Check if table exists
88
        $tableExists = $wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName;
89
        if ($tableExists) {
90
            $charset_collate = $wpdb->get_charset_collate();
91
            $sql = "CREATE TABLE IF NOT EXISTS $tableName (
92
                                id int NOT NULL AUTO_INCREMENT, 
93
                                config varchar(60) NOT NULL, 
94
                                value varchar(100) NOT NULL, 
95
                                UNIQUE KEY id(id)) $charset_collate";
96
97
            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...
98
            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

98
            /** @scrutinizer ignore-call */ 
99
            dbDelta($sql);
Loading history...
99
        }
100
101
        $dbConfigs = $wpdb->get_results("select * 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...
102
103
        // Convert a multimple dimension array for SQL insert statements into a simple key/value
104
        $simpleDbConfigs = array();
105
        foreach ($dbConfigs as $config) {
106
            $simpleDbConfigs[$config['config']] = $config['value'];
107
        }
108
        $newConfigs = array_diff_key($this->defaultConfigs, $simpleDbConfigs);
109
        if (!empty($newConfigs)) {
110
            foreach ($newConfigs as $key => $value) {
111
                $wpdb->insert($tableName, array('config' => $key, 'value'  => $value), array('%s', '%s'));
112
            }
113
        }
114
115
        foreach (array_merge($this->defaultConfigs, $simpleDbConfigs) as $key => $value) {
116
            putenv($key . '=' . $value);
117
        }
118
119
        //Current plugin config: pagantis_public_key => New field --- public_key => Old field
120
        $settings = get_option('woocommerce_pagantis_settings');
0 ignored issues
show
Bug introduced by
The function get_option was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

120
        $settings = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
121
122
        if (!isset($settings['pagantis_public_key']) && $settings['public_key']) {
123
            $settings['pagantis_public_key'] = $settings['public_key'];
124
            unset($settings['public_key']);
125
        }
126
127
        if (!isset($settings['pagantis_private_key']) && $settings['secret_key']) {
128
            $settings['pagantis_private_key'] = $settings['secret_key'];
129
            unset($settings['secret_key']);
130
        }
131
132
        update_option('woocommerce_pagantis_settings', $settings);
0 ignored issues
show
Bug introduced by
The function update_option was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

132
        /** @scrutinizer ignore-call */ 
133
        update_option('woocommerce_pagantis_settings', $settings);
Loading history...
133
    }
134
135
    /**
136
     * Product simulator
137
     */
138
    public function pagantisAddProductSimulator()
139
    {
140
        global $product;
141
142
        $cfg = get_option('woocommerce_pagantis_settings');
0 ignored issues
show
Bug introduced by
The function get_option was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

142
        $cfg = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
143
        if ($cfg['enabled'] !== 'yes' || $cfg['pagantis_public_key'] == '' || $cfg['pagantis_private_key'] == '' ||
144
            $cfg['simulator'] !== 'yes') {
145
            return;
146
        }
147
148
        $template_fields = array(
149
            'total'    => is_numeric($product->price) ? $product->price : 0,
150
            'public_key' => $cfg['pagantis_public_key'],
151
            'simulator_type' => getenv('PAGANTIS_SIMULATOR_DISPLAY_TYPE'),
152
            'positionSelector' => getenv('PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'),
153
            'quantitySelector' => getenv('PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'),
154
            'priceSelector' => getenv('PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'),
155
            'totalAmount' => is_numeric($product->price) ? $product->price : 0
156
        );
157
        wc_get_template('product_simulator.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

157
        /** @scrutinizer ignore-call */ 
158
        wc_get_template('product_simulator.php', $template_fields, '', $this->template_path);
Loading history...
158
    }
159
160
    /**
161
     * Add Pagantis to payments list.
162
     *
163
     * @param $methods
164
     *
165
     * @return array
166
     */
167
    public function addPagantisGateway($methods)
168
    {
169
        if (! class_exists('WC_Payment_Gateway')) {
170
            return $methods;
171
        }
172
173
        include_once('controllers/paymentController.php');
174
        $methods[] = 'WcPagantisGateway';
175
176
        return $methods;
177
    }
178
179
    /**
180
     * Initialize WC_Pagantis class
181
     *
182
     * @param $methods
183
     *
184
     * @return mixed
185
     */
186
    public function pagantisFilterGateways($methods)
187
    {
188
        global $woocommerce;
189
        $pagantis = new WcPagantisGateway();
0 ignored issues
show
Unused Code introduced by
The assignment to $pagantis is dead and can be removed.
Loading history...
190
191
        return $methods;
192
    }
193
194
    /**
195
     * Add links to Plugin description
196
     *
197
     * @param $links
198
     *
199
     * @return mixed
200
     */
201
    public function pagantisActionLinks($links)
202
    {
203
        $params_array = array('page' => 'wc-settings', 'tab' => 'checkout', 'section' => 'pagantis');
204
        $setting_url  = esc_url(add_query_arg($params_array, admin_url('admin.php?')));
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

204
        $setting_url  = /** @scrutinizer ignore-call */ esc_url(add_query_arg($params_array, admin_url('admin.php?')));
Loading history...
Bug introduced by
The function admin_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

204
        $setting_url  = esc_url(add_query_arg($params_array, /** @scrutinizer ignore-call */ admin_url('admin.php?')));
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

204
        $setting_url  = esc_url(/** @scrutinizer ignore-call */ add_query_arg($params_array, admin_url('admin.php?')));
Loading history...
205
        $setting_link = '<a href="'.$setting_url.'">'.__('Settings', 'pagantis').'</a>';
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

205
        $setting_link = '<a href="'.$setting_url.'">'./** @scrutinizer ignore-call */ __('Settings', 'pagantis').'</a>';
Loading history...
206
207
        array_unshift($links, $setting_link);
208
209
        return $links;
210
    }
211
212
    /**
213
     * Add links to Plugin options
214
     *
215
     * @param $links
216
     * @param $file
217
     *
218
     * @return array
219
     */
220
    public function pagantisRowMeta($links, $file)
221
    {
222
        if ($file == plugin_basename(__FILE__)) {
0 ignored issues
show
Bug introduced by
The function plugin_basename 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

222
        if ($file == /** @scrutinizer ignore-call */ plugin_basename(__FILE__)) {
Loading history...
223
            $links[] = '<a href="'.WcPagantis::GIT_HUB_URL.'" target="_blank">'.__('Documentation', 'pagantis').'</a>';
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

223
            $links[] = '<a href="'.WcPagantis::GIT_HUB_URL.'" target="_blank">'./** @scrutinizer ignore-call */ __('Documentation', 'pagantis').'</a>';
Loading history...
224
            $links[] = '<a href="'.WcPagantis::PAGANTIS_DOC_URL.'" target="_blank">'.
225
            __('API documentation', 'pagantis').'</a>';
226
            $links[] = '<a href="'.WcPagantis::SUPPORT_EML.'">'.__('Support', 'pagantis').'</a>';
227
228
            return $links;
229
        }
230
231
        return $links;
232
    }
233
234
    /**
235
     * Read logs
236
     */
237
    public function readLogs($data)
238
    {
239
        global $wpdb;
240
        $filters   = ($data->get_params());
241
        $response  = array();
242
        $secretKey = $filters['secret'];
243
        $from = $filters['from'];
244
        $to   = $filters['to'];
245
        $cfg  = get_option('woocommerce_pagantis_settings');
0 ignored issues
show
Bug introduced by
The function get_option was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

245
        $cfg  = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
246
        $privateKey = isset($cfg['secret_key']) ? $cfg['secret_key'] : null;
247
        $tableName = $wpdb->prefix.self::LOGS_TABLE;
248
        $query = "select * from $tableName where createdAt>$from and createdAt<$to order by createdAt desc";
249
        $results = $wpdb->get_results($query);
250
        if (isset($results) && $privateKey == $secretKey) {
251
            foreach ($results as $key => $result) {
252
                $response[$key]['timestamp'] = $result->createdAt;
253
                $response[$key]['log']       = json_decode($result->log);
254
            }
255
        } else {
256
            $response['result'] = 'Error';
257
        }
258
        $response = json_encode($response);
259
        header("HTTP/1.1 200", true, 200);
260
        header('Content-Type: application/json', true);
261
        header('Content-Length: '.strlen($response));
262
        echo($response);
263
        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...
264
    }
265
266
    /**
267
     * Update extra config
268
     */
269
    public function updateExtraConfig($data)
270
    {
271
        global $wpdb;
272
        $tableName = $wpdb->prefix.self::CONFIG_TABLE;
273
        $response = array('status'=>null);
274
275
        $filters   = ($data->get_params());
276
        $secretKey = $filters['secret'];
277
        $cfg  = get_option('woocommerce_pagantis_settings');
0 ignored issues
show
Bug introduced by
The function get_option was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

277
        $cfg  = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
278
        $privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
279
        if ($privateKey != $secretKey) {
280
            $response['status'] = 401;
281
            $response['result'] = 'Unauthorized';
282
        } elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
283
            if (count($_POST)) {
284
                foreach ($_POST as $config => $value) {
285
                    if (isset($this->defaultConfigs[$config]) && $response['status']==null) {
286
                        $wpdb->update(
287
                            $tableName,
288
                            array('value' => $value),
289
                            array('config' => $config),
290
                            array('%s'),
291
                            array('%s')
292
                        );
293
                    } else {
294
                        $response['status'] = 400;
295
                        $response['result'] = 'Bad request';
296
                    }
297
                }
298
            } else {
299
                $response['status'] = 422;
300
                $response['result'] = 'Empty data';
301
            }
302
        }
303
304
        if ($response['status']==null) {
305
            $tableName = $wpdb->prefix.self::CONFIG_TABLE;
306
            $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...
307
            foreach ($dbResult as $value) {
308
                $formattedResult[$value['config']] = $value['value'];
309
            }
310
            $response['result'] = $formattedResult;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $formattedResult seems to be defined by a foreach iteration on line 307. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
311
        }
312
313
        $result = json_encode($response['result']);
314
        header("HTTP/1.1 ".$response['status'], true, $response['status']);
315
        header('Content-Type: application/json', true);
316
        header('Content-Length: '.strlen($result));
317
        echo($result);
318
        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...
319
    }
320
321
    /**
322
     * ENDPOINT - Read logs -> Hook: rest_api_init
323
     * @return mixed
324
     */
325
    public function pagantisRegisterEndpoint()
326
    {
327
        register_rest_route(
0 ignored issues
show
Bug introduced by
The function register_rest_route 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

327
        /** @scrutinizer ignore-call */ 
328
        register_rest_route(
Loading history...
328
            'pagantis/v1',
329
            '/logs/(?P<secret>\w+)/(?P<from>\d+)/(?P<to>\d+)',
330
            array(
331
            'methods'  => 'GET',
332
            'callback' => array(
333
                $this,
334
                'readLogs')
335
            ),
336
            true
337
        );
338
339
        register_rest_route(
340
            'pagantis/v1',
341
            '/configController/(?P<secret>\w+)',
342
            array(
343
                'methods'  => 'GET, POST',
344
                'callback' => array(
345
                    $this,
346
                    'updateExtraConfig')
347
            ),
348
            true
349
        );
350
    }
351
}
352
353
/**
354
 * Add widget Js
355
 **/
356
function add_widget_js()
357
{
358
    wp_enqueue_script('pmtSdk', 'https://cdn.pagamastarde.com/js/pmt-v2/sdk.js', '', '', true);
0 ignored issues
show
Bug introduced by
The function wp_enqueue_script 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

358
    /** @scrutinizer ignore-call */ 
359
    wp_enqueue_script('pmtSdk', 'https://cdn.pagamastarde.com/js/pmt-v2/sdk.js', '', '', true);
Loading history...
359
}
360
361
new WcPagantis();
362