Passed
Pull Request — master (#22)
by
unknown
02:37
created

WcPagantis   F

Complexity

Total Complexity 69

Size/Duplication

Total Lines 496
Duplicated Lines 0 %

Importance

Changes 10
Bugs 0 Features 0
Metric Value
eloc 273
c 10
b 0
f 0
dl 0
loc 496
rs 2.88
wmc 69

15 Methods

Rating   Name   Duplication   Size   Complexity  
A loadPagantisTranslation() 0 6 2
A pagantisActionLinks() 0 9 1
A pagantisFilterGateways() 0 8 2
A pagantisRowMeta() 0 12 2
A addPagantisGateway() 0 10 2
A prepareQuantitySelector() 0 9 4
C pagantisActivation() 0 95 16
A preparePriceSelector() 0 9 4
B updateExtraConfig() 0 50 10
A pagantisRegisterEndpoint() 0 36 1
A __construct() 0 19 1
B readApi() 0 34 8
B pagantisAddProductSimulator() 0 25 9
A getExtraConfig() 0 11 2
A readLogs() 0 27 5

How to fix   Complexity   

Complex Class

Complex classes like WcPagantis often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use WcPagantis, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Plugin Name: Pagantis
4
 * Plugin URI: http://www.pagantis.com/
5
 * Description: Financiar con Pagantis
6
 * Version: 8.1.3
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.pagantis.com';
21
    const SUPPORT_EML = 'mailto:[email protected]?Subject=woocommerce_plugin';
22
23
    /** Concurrency tablename */
24
    const LOGS_TABLE = 'pagantis_logs';
25
26
    /** Config tablename */
27
    const CONFIG_TABLE = 'pagantis_config';
28
29
    /** Concurrency tablename  */
30
    const CONCURRENCY_TABLE = 'pagantis_concurrency';
31
32
    /** Config tablename */
33
    const ORDERS_TABLE = 'posts';
34
35
    public $defaultConfigs = array('PAGANTIS_TITLE'=>'Instant Financing',
36
                            'PAGANTIS_SIMULATOR_DISPLAY_TYPE'=>'pgSDK.simulator.types.SIMPLE',
37
                            'PAGANTIS_SIMULATOR_DISPLAY_SKIN'=>'pgSDK.simulator.skins.BLUE',
38
                            'PAGANTIS_SIMULATOR_DISPLAY_POSITION'=>'hookDisplayProductButtons',
39
                            'PAGANTIS_SIMULATOR_START_INSTALLMENTS'=>3,
40
                            'PAGANTIS_SIMULATOR_MAX_INSTALLMENTS'=>12,
41
                            'PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'=>'default',
42
                            'PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION'=>'pgSDK.simulator.positions.INNER',
43
                            'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'=>'a:3:{i:0;s:48:"div.summary *:not(del)>.woocommerce-Price-amount";i:1;s:54:"div.entry-summary *:not(del)>.woocommerce-Price-amount";i:2;s:36:"*:not(del)>.woocommerce-Price-amount";}',
44
                            'PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'=>'a:2:{i:0;s:22:"div.quantity input.qty";i:1;s:18:"div.quantity>input";}',
45
                            'PAGANTIS_FORM_DISPLAY_TYPE'=>0,
46
                            'PAGANTIS_DISPLAY_MIN_AMOUNT'=>1,
47
                            'PAGANTIS_URL_OK'=>'',
48
                            'PAGANTIS_URL_KO'=>'',
49
                            'PAGANTIS_ALLOWED_COUNTRIES' => 'a:2:{i:0;s:2:"es";i:1;s:2:"it";}'
50
    );
51
52
    /** @var Array $extraConfig */
53
    public $extraConfig;
54
55
    /**
56
     * WC_Pagantis constructor.
57
     */
58
    public function __construct()
59
    {
60
        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

60
        require_once(/** @scrutinizer ignore-call */ plugin_dir_path(__FILE__).'/vendor/autoload.php');
Loading history...
61
62
        $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...
63
64
        $this->extraConfig = $this->getExtraConfig();
65
66
        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

66
        /** @scrutinizer ignore-call */ 
67
        load_plugin_textdomain('pagantis', false, basename(dirname(__FILE__)).'/languages');
Loading history...
67
        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

67
        /** @scrutinizer ignore-call */ 
68
        add_filter('woocommerce_payment_gateways', array($this, 'addPagantisGateway'));
Loading history...
68
        add_filter('woocommerce_available_payment_gateways', array($this, 'pagantisFilterGateways'), 9999);
69
        add_filter('plugin_row_meta', array($this, 'pagantisRowMeta'), 10, 2);
70
        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

70
        add_filter('plugin_action_links_'./** @scrutinizer ignore-call */ plugin_basename(__FILE__), array($this, 'pagantisActionLinks'));
Loading history...
71
        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

71
        /** @scrutinizer ignore-call */ 
72
        add_action('woocommerce_after_add_to_cart_form', array($this, 'pagantisAddProductSimulator'));
Loading history...
72
        add_action('wp_enqueue_scripts', 'add_pagantis_widget_js');
73
        add_action('rest_api_init', array($this, 'pagantisRegisterEndpoint')); //Endpoint
74
        add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
75
        //add_action('upgrader_process_complete', 'pagantisActivation', 10, 2);
76
        register_activation_hook(__FILE__, array($this, 'pagantisActivation'));
0 ignored issues
show
Bug introduced by
The function register_activation_hook 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 */ 
77
        register_activation_hook(__FILE__, array($this, 'pagantisActivation'));
Loading history...
77
    }
78
79
    /*
80
     * Replace 'textdomain' with your plugin's textdomain. e.g. 'woocommerce'.
81
     * File to be named, for example, yourtranslationfile-en_GB.mo
82
     * File to be placed, for example, wp-content/lanaguages/textdomain/yourtranslationfile-en_GB.mo
83
     */
84
    public function loadPagantisTranslation($mofile, $domain)
85
    {
86
        if ('pagantis' === $domain) {
87
            $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

87
            $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...
88
        }
89
        return $mofile;
90
    }
91
92
    /**
93
     * Sql table
94
     */
95
    public function pagantisActivation()
96
    {
97
        global $wpdb;
98
99
        $tableName = $wpdb->prefix.self::CONCURRENCY_TABLE;
100
        if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName) {
101
            $charset_collate = $wpdb->get_charset_collate();
102
            $sql = "CREATE TABLE $tableName ( order_id int NOT NULL,  
103
                    createdAt timestamp DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY id (order_id)) $charset_collate";
104
            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...
105
            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

105
            /** @scrutinizer ignore-call */ 
106
            dbDelta($sql);
Loading history...
106
        }
107
108
        $tableName = $wpdb->prefix.self::CONFIG_TABLE;
109
110
        //Check if table exists
111
        $tableExists = $wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName;
112
        if ($tableExists) {
113
            $charset_collate = $wpdb->get_charset_collate();
114
            $sql = "CREATE TABLE IF NOT EXISTS $tableName (
115
                                id int NOT NULL AUTO_INCREMENT, 
116
                                config varchar(60) NOT NULL, 
117
                                value varchar(1000) NOT NULL, 
118
                                UNIQUE KEY id(id)) $charset_collate";
119
120
            require_once(ABSPATH.'wp-admin/includes/upgrade.php');
121
            dbDelta($sql);
122
        } else {
123
            //Updated value field to adapt to new length < v8.0.1
124
            $query = "select COLUMN_TYPE FROM information_schema.COLUMNS where TABLE_NAME='$tableName' AND COLUMN_NAME='value'";
125
            $results = $wpdb->get_results($query, 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...
126
            if ($results['0']['COLUMN_TYPE'] == 'varchar(100)') {
127
                $sql = "ALTER TABLE $tableName MODIFY value varchar(1000)";
128
                $wpdb->query($sql);
129
            }
130
131
            //Adapting selector to array
132
            $query = "select * from $tableName where config='PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR' 
133
                               or config='PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'";
134
            $dbCurrentConfig = $wpdb->get_results($query, ARRAY_A);
135
            foreach ($dbCurrentConfig as $item) {
136
                if ($item['config'] == 'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR') {
137
                    $css_price_selector = $this->preparePriceSelector($item['value']);
138
                    if ($item['value'] != $css_price_selector) {
139
                        $wpdb->update(
140
                            $tableName,
141
                            array('value' => stripslashes($css_price_selector)),
142
                            array('config' => 'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'),
143
                            array('%s'),
144
                            array('%s')
145
                        );
146
                    }
147
                } elseif ($item['config'] == 'PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR') {
148
                    $css_quantity_selector = $this->prepareQuantitySelector($item['value']);
149
                    if ($item['value'] != $css_quantity_selector) {
150
                        $wpdb->update(
151
                            $tableName,
152
                            array('value' => stripslashes($css_quantity_selector)),
153
                            array('config' => 'PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'),
154
                            array('%s'),
155
                            array('%s')
156
                        );
157
                    }
158
                }
159
            }
160
        }
161
162
        $dbConfigs = $wpdb->get_results("select * from $tableName", ARRAY_A);
163
164
        // Convert a multimple dimension array for SQL insert statements into a simple key/value
165
        $simpleDbConfigs = array();
166
        foreach ($dbConfigs as $config) {
167
            $simpleDbConfigs[$config['config']] = $config['value'];
168
        }
169
        $newConfigs = array_diff_key($this->defaultConfigs, $simpleDbConfigs);
170
        if (!empty($newConfigs)) {
171
            foreach ($newConfigs as $key => $value) {
172
                $wpdb->insert($tableName, array('config' => $key, 'value'  => $value), array('%s', '%s'));
173
            }
174
        }
175
176
        //Current plugin config: pagantis_public_key => New field --- public_key => Old field
177
        $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

177
        $settings = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
178
179
        if (!isset($settings['pagantis_public_key']) && $settings['public_key']) {
180
            $settings['pagantis_public_key'] = $settings['public_key'];
181
            unset($settings['public_key']);
182
        }
183
184
        if (!isset($settings['pagantis_private_key']) && $settings['secret_key']) {
185
            $settings['pagantis_private_key'] = $settings['secret_key'];
186
            unset($settings['secret_key']);
187
        }
188
189
        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

189
        /** @scrutinizer ignore-call */ 
190
        update_option('woocommerce_pagantis_settings', $settings);
Loading history...
190
    }
191
192
    /**
193
     * Product simulator
194
     */
195
    public function pagantisAddProductSimulator()
196
    {
197
        global $product;
198
199
        $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

199
        $cfg = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
200
        $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

200
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
201
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
202
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
203
        if ($cfg['enabled'] !== 'yes' || $cfg['pagantis_public_key'] == '' || $cfg['pagantis_private_key'] == '' ||
204
            $cfg['simulator'] !== 'yes' ||  $product->price < $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'] ||
205
            !$allowedCountry ) {
206
            return;
207
        }
208
209
        $template_fields = array(
210
            'total'    => is_numeric($product->price) ? $product->price : 0,
211
            'public_key' => $cfg['pagantis_public_key'],
212
            'simulator_type' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE'],
213
            'positionSelector' => $this->extraConfig['PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'],
214
            'quantitySelector' => unserialize($this->extraConfig['PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR']),
215
            'priceSelector' => unserialize($this->extraConfig['PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR']),
216
            'totalAmount' => is_numeric($product->price) ? $product->price : 0,
217
            'locale' => $locale
218
        );
219
        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

219
        /** @scrutinizer ignore-call */ 
220
        wc_get_template('product_simulator.php', $template_fields, '', $this->template_path);
Loading history...
220
    }
221
222
    /**
223
     * Add Pagantis to payments list.
224
     *
225
     * @param $methods
226
     *
227
     * @return array
228
     */
229
    public function addPagantisGateway($methods)
230
    {
231
        if (! class_exists('WC_Payment_Gateway')) {
232
            return $methods;
233
        }
234
235
        include_once('controllers/paymentController.php');
236
        $methods[] = 'WcPagantisGateway';
237
238
        return $methods;
239
    }
240
241
    /**
242
     * Initialize WC_Pagantis class
243
     *
244
     * @param $methods
245
     *
246
     * @return mixed
247
     */
248
    public function pagantisFilterGateways($methods)
249
    {
250
        $pagantis = new WcPagantisGateway();
251
        if (!$pagantis->is_available()) {
252
            unset($methods['pagantis']);
253
        }
254
255
        return $methods;
256
    }
257
258
    /**
259
     * Add links to Plugin description
260
     *
261
     * @param $links
262
     *
263
     * @return mixed
264
     */
265
    public function pagantisActionLinks($links)
266
    {
267
        $params_array = array('page' => 'wc-settings', 'tab' => 'checkout', 'section' => 'pagantis');
268
        $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

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

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

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

269
        $setting_link = '<a href="'.$setting_url.'">'./** @scrutinizer ignore-call */ __('Settings', 'pagantis').'</a>';
Loading history...
270
271
        array_unshift($links, $setting_link);
272
273
        return $links;
274
    }
275
276
    /**
277
     * Add links to Plugin options
278
     *
279
     * @param $links
280
     * @param $file
281
     *
282
     * @return array
283
     */
284
    public function pagantisRowMeta($links, $file)
285
    {
286
        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

286
        if ($file == /** @scrutinizer ignore-call */ plugin_basename(__FILE__)) {
Loading history...
287
            $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

287
            $links[] = '<a href="'.WcPagantis::GIT_HUB_URL.'" target="_blank">'./** @scrutinizer ignore-call */ __('Documentation', 'pagantis').'</a>';
Loading history...
288
            $links[] = '<a href="'.WcPagantis::PAGANTIS_DOC_URL.'" target="_blank">'.
289
            __('API documentation', 'pagantis').'</a>';
290
            $links[] = '<a href="'.WcPagantis::SUPPORT_EML.'">'.__('Support', 'pagantis').'</a>';
291
292
            return $links;
293
        }
294
295
        return $links;
296
    }
297
298
    /**
299
     * Read logs
300
     */
301
    public function readLogs($data)
302
    {
303
        global $wpdb;
304
        $filters   = ($data->get_params());
305
        $response  = array();
306
        $secretKey = $filters['secret'];
307
        $from = $filters['from'];
308
        $to   = $filters['to'];
309
        $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

309
        $cfg  = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
310
        $privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
311
        $tableName = $wpdb->prefix.self::LOGS_TABLE;
312
        $query = "select * from $tableName where createdAt>$from and createdAt<$to order by createdAt desc";
313
        $results = $wpdb->get_results($query);
314
        if (isset($results) && $privateKey == $secretKey) {
315
            foreach ($results as $key => $result) {
316
                $response[$key]['timestamp'] = $result->createdAt;
317
                $response[$key]['log']       = json_decode($result->log);
318
            }
319
        } else {
320
            $response['result'] = 'Error';
321
        }
322
        $response = json_encode($response);
323
        header("HTTP/1.1 200", true, 200);
324
        header('Content-Type: application/json', true);
325
        header('Content-Length: '.strlen($response));
326
        echo($response);
327
        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...
328
    }
329
330
    /**
331
     * Update extra config
332
     */
333
    public function updateExtraConfig($data)
334
    {
335
        global $wpdb;
336
        $tableName = $wpdb->prefix.self::CONFIG_TABLE;
337
        $response = array('status'=>null);
338
339
        $filters   = ($data->get_params());
340
        $secretKey = $filters['secret'];
341
        $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

341
        $cfg  = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
342
        $privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
343
        if ($privateKey != $secretKey) {
344
            $response['status'] = 401;
345
            $response['result'] = 'Unauthorized';
346
        } elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
347
            if (count($_POST)) {
348
                foreach ($_POST as $config => $value) {
349
                    if (isset($this->defaultConfigs[$config]) && $response['status']==null) {
350
                        $wpdb->update(
351
                            $tableName,
352
                            array('value' => stripslashes($value)),
353
                            array('config' => $config),
354
                            array('%s'),
355
                            array('%s')
356
                        );
357
                    } else {
358
                        $response['status'] = 400;
359
                        $response['result'] = 'Bad request';
360
                    }
361
                }
362
            } else {
363
                $response['status'] = 422;
364
                $response['result'] = 'Empty data';
365
            }
366
        }
367
368
        if ($response['status']==null) {
369
            $tableName = $wpdb->prefix.self::CONFIG_TABLE;
370
            $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...
371
            foreach ($dbResult as $value) {
372
                $formattedResult[$value['config']] = $value['value'];
373
            }
374
            $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 371. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
375
        }
376
377
        $result = json_encode($response['result']);
378
        header("HTTP/1.1 ".$response['status'], true, $response['status']);
379
        header('Content-Type: application/json', true);
380
        header('Content-Length: '.strlen($result));
381
        echo($result);
382
        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...
383
    }
384
385
    /**
386
     * Read logs
387
     */
388
    public function readApi($data)
389
    {
390
        global $wpdb;
391
        $filters   = ($data->get_params());
392
        $response  = array('timestamp'=>time());
393
        $secretKey = $filters['secret'];
394
        $from = ($filters['from']) ? date_create($filters['from']) : date("Y-m-d", strtotime("-7 day"));
395
        $to = ($filters['to']) ? date_create($filters['to']) : date("Y-m-d", strtotime("+1 day"));
396
        $method = ($filters['method']) ? ($filters['method']) : 'Pagantis';
0 ignored issues
show
Unused Code introduced by
The assignment to $method is dead and can be removed.
Loading history...
397
        $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

397
        $cfg  = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
398
        $privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
399
        $tableName = $wpdb->prefix.self::ORDERS_TABLE;
400
        $tableNameInner = $wpdb->prefix.'postmeta';
401
        $query = "select * from $tableName tn
402
INNER JOIN $tableNameInner tn2 ON tn2.post_id = tn.id
403
where tn.post_type='shop_order' and tn.post_date>'".$from->format("Y-m-d")."' and tn.post_date<'".$to->format("Y-m-d")."' order by tn.post_date desc";
404
        $results = $wpdb->get_results($query);
405
406
        if (isset($results) && $privateKey == $secretKey) {
407
            foreach ($results as $result) {
408
                $key = $result->ID;
409
                $response['message'][$key]['timestamp'] = $result->post_date;
410
                $response['message'][$key]['order_id'] = $key;
411
                $response['message'][$key][$result->meta_key] = $result->meta_value;
412
            }
413
        } else {
414
            $response['result'] = 'Error';
415
        }
416
        $response = json_encode($response);
417
        header("HTTP/1.1 200", true, 200);
418
        header('Content-Type: application/json', true);
419
        header('Content-Length: '.strlen($response));
420
        echo($response);
421
        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...
422
    }
423
424
    /**
425
     * ENDPOINT - Read logs -> Hook: rest_api_init
426
     * @return mixed
427
     */
428
    public function pagantisRegisterEndpoint()
429
    {
430
        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

430
        /** @scrutinizer ignore-call */ 
431
        register_rest_route(
Loading history...
431
            'pagantis/v1',
432
            '/logs/(?P<secret>\w+)/(?P<from>\d+)/(?P<to>\d+)',
433
            array(
434
            'methods'  => 'GET',
435
            'callback' => array(
436
                $this,
437
                'readLogs')
438
            ),
439
            true
440
        );
441
442
        register_rest_route(
443
            'pagantis/v1',
444
            '/configController/(?P<secret>\w+)',
445
            array(
446
                'methods'  => 'GET, POST',
447
                'callback' => array(
448
                    $this,
449
                    'updateExtraConfig')
450
            ),
451
            true
452
        );
453
454
        register_rest_route(
455
            'pagantis/v1',
456
            '/api/(?P<secret>\w+)/(?P<from>\w+)/(?P<to>\w+)',
457
            array(
458
                'methods'  => 'GET',
459
                'callback' => array(
460
                    $this,
461
                    'readApi')
462
            ),
463
            true
464
        );
465
    }
466
467
    /**
468
     * @return array
469
     */
470
    private function getExtraConfig()
471
    {
472
        global $wpdb;
473
        $tableName = $wpdb->prefix.self::CONFIG_TABLE;
474
        $response = array();
475
        $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...
476
        foreach ($dbResult as $value) {
477
            $response[$value['config']] = $value['value'];
478
        }
479
480
        return $response;
481
    }
482
483
    /**
484
     * @param $css_quantity_selector
485
     *
486
     * @return mixed|string
487
     */
488
    private function prepareQuantitySelector($css_quantity_selector)
489
    {
490
        if ($css_quantity_selector == 'default' || $css_quantity_selector == '') {
491
            $css_quantity_selector = $this->defaultConfigs['PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'];
492
        } elseif (!unserialize($css_quantity_selector)) { //in the case of a custom string selector, we keep it
493
            $css_quantity_selector = serialize(array($css_quantity_selector));
494
        }
495
496
        return $css_quantity_selector;
497
    }
498
499
    /**
500
     * @param $css_price_selector
501
     *
502
     * @return mixed|string
503
     */
504
    private function preparePriceSelector($css_price_selector)
505
    {
506
        if ($css_price_selector == 'default' || $css_price_selector == '') {
507
            $css_price_selector = $this->defaultConfigs['PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'];
508
        } elseif (!unserialize($css_price_selector)) { //in the case of a custom string selector, we keep it
509
            $css_price_selector = serialize(array($css_price_selector));
510
        }
511
512
        return $css_price_selector;
513
    }
514
}
515
516
/**
517
 * Add widget Js
518
 **/
519
function add_pagantis_widget_js()
520
{
521
    wp_enqueue_script('pgSDK', 'https://cdn.pagantis.com/js/pg-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

521
    /** @scrutinizer ignore-call */ 
522
    wp_enqueue_script('pgSDK', 'https://cdn.pagantis.com/js/pg-v2/sdk.js', '', '', true);
Loading history...
522
    wp_enqueue_script('pmtSDK', 'https://cdn.pagamastarde.com/js/pmt-v2/sdk.js', '', '', true);
523
}
524
525
$WcPagantis = new WcPagantis();
526