Completed
Push — master ( bf6bef...e00620 )
by
unknown
38s queued 31s
created

WcPagantis::pagantisActivation()   C

Complexity

Conditions 16
Paths 96

Size

Total Lines 95
Code Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 16
eloc 59
c 3
b 0
f 0
nc 96
nop 0
dl 0
loc 95
rs 5.5666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

75
        /** @scrutinizer ignore-call */ 
76
        register_activation_hook(__FILE__, array($this, 'pagantisActivation'));
Loading history...
76
    }
77
78
    /*
79
     * Replace 'textdomain' with your plugin's textdomain. e.g. 'woocommerce'.
80
     * File to be named, for example, yourtranslationfile-en_GB.mo
81
     * File to be placed, for example, wp-content/lanaguages/textdomain/yourtranslationfile-en_GB.mo
82
     */
83
    public function loadPagantisTranslation($mofile, $domain)
84
    {
85
        if ('pagantis' === $domain) {
86
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . get_locale() . '.mo';
0 ignored issues
show
Bug introduced by
The constant WP_LANG_DIR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
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

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

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

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

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

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

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

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

267
        $setting_url  = /** @scrutinizer ignore-call */ esc_url(add_query_arg($params_array, 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

267
        $setting_url  = esc_url(/** @scrutinizer ignore-call */ 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

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

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

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

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

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

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

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

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

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