Passed
Pull Request — master (#22)
by Cesar
05:36 queued 02:58
created

WcPagantis::readApi()   B

Complexity

Conditions 8
Paths 32

Size

Total Lines 34
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 29
c 1
b 0
f 0
nc 32
nop 1
dl 0
loc 34
rs 8.2114
1
<?php
2
/**
3
 * Plugin Name: Pagantis
4
 * Plugin URI: http://www.pagantis.com/
5
 * Description: Financiar con Pagantis
6
 * Version: 8.1.2
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->pagantisActivation();
65
66
        $this->extraConfig = $this->getExtraConfig();
67
68
        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

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

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

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

73
        /** @scrutinizer ignore-call */ 
74
        add_action('woocommerce_after_add_to_cart_form', array($this, 'pagantisAddProductSimulator'));
Loading history...
74
        add_action('wp_enqueue_scripts', 'add_pagantis_widget_js');
75
        add_action('rest_api_init', array($this, 'pagantisRegisterEndpoint')); //Endpoint
76
        add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
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
        }
123
124
        $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...
125
126
        // Convert a multimple dimension array for SQL insert statements into a simple key/value
127
        $simpleDbConfigs = array();
128
        foreach ($dbConfigs as $config) {
129
            $simpleDbConfigs[$config['config']] = $config['value'];
130
        }
131
        $newConfigs = array_diff_key($this->defaultConfigs, $simpleDbConfigs);
132
        if (!empty($newConfigs)) {
133
            foreach ($newConfigs as $key => $value) {
134
                $wpdb->insert($tableName, array('config' => $key, 'value'  => $value), array('%s', '%s'));
135
            }
136
        }
137
138
        //Current plugin config: pagantis_public_key => New field --- public_key => Old field
139
        $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

139
        $settings = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
140
141
        if (!isset($settings['pagantis_public_key']) && $settings['public_key']) {
142
            $settings['pagantis_public_key'] = $settings['public_key'];
143
            unset($settings['public_key']);
144
        }
145
146
        if (!isset($settings['pagantis_private_key']) && $settings['secret_key']) {
147
            $settings['pagantis_private_key'] = $settings['secret_key'];
148
            unset($settings['secret_key']);
149
        }
150
151
        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

151
        /** @scrutinizer ignore-call */ 
152
        update_option('woocommerce_pagantis_settings', $settings);
Loading history...
152
    }
153
154
    /**
155
     * Product simulator
156
     */
157
    public function pagantisAddProductSimulator()
158
    {
159
        global $product;
160
161
        $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

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

162
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
163
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
164
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
165
        if ($cfg['enabled'] !== 'yes' || $cfg['pagantis_public_key'] == '' || $cfg['pagantis_private_key'] == '' ||
166
            $cfg['simulator'] !== 'yes' ||  $product->price < $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'] ||
167
            !$allowedCountry ) {
168
            return;
169
        }
170
171
        $css_quantity_selector = $this->prepareQuantitySelector();
172
        $css_price_selector = $this->preparePriceSelector();
173
        $template_fields = array(
174
            'total'    => is_numeric($product->price) ? $product->price : 0,
175
            'public_key' => $cfg['pagantis_public_key'],
176
            'simulator_type' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE'],
177
            'positionSelector' => $this->extraConfig['PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'],
178
            'quantitySelector' => unserialize($css_quantity_selector),
179
            'priceSelector' => unserialize($css_price_selector),
180
            'totalAmount' => is_numeric($product->price) ? $product->price : 0,
181
            'locale' => $locale
182
        );
183
        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

183
        /** @scrutinizer ignore-call */ 
184
        wc_get_template('product_simulator.php', $template_fields, '', $this->template_path);
Loading history...
184
    }
185
186
    /**
187
     * Add Pagantis to payments list.
188
     *
189
     * @param $methods
190
     *
191
     * @return array
192
     */
193
    public function addPagantisGateway($methods)
194
    {
195
        if (! class_exists('WC_Payment_Gateway')) {
196
            return $methods;
197
        }
198
199
        include_once('controllers/paymentController.php');
200
        $methods[] = 'WcPagantisGateway';
201
202
        return $methods;
203
    }
204
205
    /**
206
     * Initialize WC_Pagantis class
207
     *
208
     * @param $methods
209
     *
210
     * @return mixed
211
     */
212
    public function pagantisFilterGateways($methods)
213
    {
214
        $pagantis = new WcPagantisGateway();
215
        if (!$pagantis->is_available()) {
216
            unset($methods['pagantis']);
217
        }
218
219
        return $methods;
220
    }
221
222
    /**
223
     * Add links to Plugin description
224
     *
225
     * @param $links
226
     *
227
     * @return mixed
228
     */
229
    public function pagantisActionLinks($links)
230
    {
231
        $params_array = array('page' => 'wc-settings', 'tab' => 'checkout', 'section' => 'pagantis');
232
        $setting_url  = esc_url(add_query_arg($params_array, admin_url('admin.php?')));
0 ignored issues
show
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

232
        $setting_url  = esc_url(/** @scrutinizer ignore-call */ add_query_arg($params_array, admin_url('admin.php?')));
Loading history...
Bug introduced by
The function esc_url was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

233
        $setting_link = '<a href="'.$setting_url.'">'./** @scrutinizer ignore-call */ __('Settings', 'pagantis').'</a>';
Loading history...
234
235
        array_unshift($links, $setting_link);
236
237
        return $links;
238
    }
239
240
    /**
241
     * Add links to Plugin options
242
     *
243
     * @param $links
244
     * @param $file
245
     *
246
     * @return array
247
     */
248
    public function pagantisRowMeta($links, $file)
249
    {
250
        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

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

251
            $links[] = '<a href="'.WcPagantis::GIT_HUB_URL.'" target="_blank">'./** @scrutinizer ignore-call */ __('Documentation', 'pagantis').'</a>';
Loading history...
252
            $links[] = '<a href="'.WcPagantis::PAGANTIS_DOC_URL.'" target="_blank">'.
253
            __('API documentation', 'pagantis').'</a>';
254
            $links[] = '<a href="'.WcPagantis::SUPPORT_EML.'">'.__('Support', 'pagantis').'</a>';
255
256
            return $links;
257
        }
258
259
        return $links;
260
    }
261
262
    /**
263
     * Read logs
264
     */
265
    public function readLogs($data)
266
    {
267
        global $wpdb;
268
        $filters   = ($data->get_params());
269
        $response  = array();
270
        $secretKey = $filters['secret'];
271
        $from = $filters['from'];
272
        $to   = $filters['to'];
273
        $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

273
        $cfg  = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
274
        $privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
275
        $tableName = $wpdb->prefix.self::LOGS_TABLE;
276
        $query = "select * from $tableName where createdAt>$from and createdAt<$to order by createdAt desc";
277
        $results = $wpdb->get_results($query);
278
        if (isset($results) && $privateKey == $secretKey) {
279
            foreach ($results as $key => $result) {
280
                $response[$key]['timestamp'] = $result->createdAt;
281
                $response[$key]['log']       = json_decode($result->log);
282
            }
283
        } else {
284
            $response['result'] = 'Error';
285
        }
286
        $response = json_encode($response);
287
        header("HTTP/1.1 200", true, 200);
288
        header('Content-Type: application/json', true);
289
        header('Content-Length: '.strlen($response));
290
        echo($response);
291
        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...
292
    }
293
294
    /**
295
     * Update extra config
296
     */
297
    public function updateExtraConfig($data)
298
    {
299
        global $wpdb;
300
        $tableName = $wpdb->prefix.self::CONFIG_TABLE;
301
        $response = array('status'=>null);
302
303
        $filters   = ($data->get_params());
304
        $secretKey = $filters['secret'];
305
        $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

305
        $cfg  = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
306
        $privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
307
        if ($privateKey != $secretKey) {
308
            $response['status'] = 401;
309
            $response['result'] = 'Unauthorized';
310
        } elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
311
            if (count($_POST)) {
312
                foreach ($_POST as $config => $value) {
313
                    if (isset($this->defaultConfigs[$config]) && $response['status']==null) {
314
                        $wpdb->update(
315
                            $tableName,
316
                            array('value' => $value),
317
                            array('config' => $config),
318
                            array('%s'),
319
                            array('%s')
320
                        );
321
                    } else {
322
                        $response['status'] = 400;
323
                        $response['result'] = 'Bad request';
324
                    }
325
                }
326
            } else {
327
                $response['status'] = 422;
328
                $response['result'] = 'Empty data';
329
            }
330
        }
331
332
        if ($response['status']==null) {
333
            $tableName = $wpdb->prefix.self::CONFIG_TABLE;
334
            $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...
335
            foreach ($dbResult as $value) {
336
                $formattedResult[$value['config']] = $value['value'];
337
            }
338
            $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 335. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
339
        }
340
341
        $result = json_encode($response['result']);
342
        header("HTTP/1.1 ".$response['status'], true, $response['status']);
343
        header('Content-Type: application/json', true);
344
        header('Content-Length: '.strlen($result));
345
        echo($result);
346
        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...
347
    }
348
349
    /**
350
     * Read logs
351
     */
352
    public function readApi($data)
353
    {
354
        global $wpdb;
355
        $filters   = ($data->get_params());
356
        $response  = array('timestamp'=>time());
357
        $secretKey = $filters['secret'];
358
        $from = ($filters['from']) ? date_create($filters['from']) : date("Y-m-d", strtotime("-7 day"));
359
        $to = ($filters['to']) ? date_create($filters['to']) : date("Y-m-d", strtotime("+1 day"));
360
        $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...
361
        $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

361
        $cfg  = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
362
        $privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
363
        $tableName = $wpdb->prefix.self::ORDERS_TABLE;
364
        $tableNameInner = $wpdb->prefix.'postmeta';
365
        $query = "select * from $tableName tn
366
INNER JOIN $tableNameInner tn2 ON tn2.post_id = tn.id
367
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";
368
        $results = $wpdb->get_results($query);
369
370
        if (isset($results) && $privateKey == $secretKey) {
371
            foreach ($results as $result) {
372
                $key = $result->ID;
373
                $response['message'][$key]['timestamp'] = $result->post_date;
374
                $response['message'][$key]['order_id'] = $key;
375
                $response['message'][$key][$result->meta_key] = $result->meta_value;
376
            }
377
        } else {
378
            $response['result'] = 'Error';
379
        }
380
        $response = json_encode($response);
381
        header("HTTP/1.1 200", true, 200);
382
        header('Content-Type: application/json', true);
383
        header('Content-Length: '.strlen($response));
384
        echo($response);
385
        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...
386
    }
387
388
    /**
389
     * ENDPOINT - Read logs -> Hook: rest_api_init
390
     * @return mixed
391
     */
392
    public function pagantisRegisterEndpoint()
393
    {
394
        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

394
        /** @scrutinizer ignore-call */ 
395
        register_rest_route(
Loading history...
395
            'pagantis/v1',
396
            '/logs/(?P<secret>\w+)/(?P<from>\d+)/(?P<to>\d+)',
397
            array(
398
            'methods'  => 'GET',
399
            'callback' => array(
400
                $this,
401
                'readLogs')
402
            ),
403
            true
404
        );
405
406
        register_rest_route(
407
            'pagantis/v1',
408
            '/configController/(?P<secret>\w+)',
409
            array(
410
                'methods'  => 'GET, POST',
411
                'callback' => array(
412
                    $this,
413
                    'updateExtraConfig')
414
            ),
415
            true
416
        );
417
418
        register_rest_route(
419
            'pagantis/v1',
420
            '/api/(?P<secret>\w+)/(?P<from>\w+)/(?P<to>\w+)',
421
            array(
422
                'methods'  => 'GET',
423
                'callback' => array(
424
                    $this,
425
                    'readApi')
426
            ),
427
            true
428
        );
429
    }
430
431
    /**
432
     * @return array
433
     */
434
    private function getExtraConfig()
435
    {
436
        global $wpdb;
437
        $tableName = $wpdb->prefix.self::CONFIG_TABLE;
438
        $response = array();
439
        $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...
440
        foreach ($dbResult as $value) {
441
            $response[$value['config']] = $value['value'];
442
        }
443
444
        return $response;
445
    }
446
447
    /**
448
     * @return mixed|string
449
     */
450
    private function prepareQuantitySelector()
451
    {
452
        $css_quantity_selector = $this->extraConfig['PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'];
453
        if ($css_quantity_selector == 'default' || $css_quantity_selector == '') {
454
            $css_quantity_selector = $this->defaultConfigs['PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'];
455
        } elseif (!unserialize($css_quantity_selector)) { //in the case of a custom string selector, we keep it
456
            $css_quantity_selector = serialize(array($css_quantity_selector));
457
        }
458
459
        return $css_quantity_selector;
460
    }
461
462
    /**
463
     * @return mixed|string
464
     */
465
    private function preparePriceSelector()
466
    {
467
        $css_price_selector = $this->extraConfig['PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'];
468
        if ($css_price_selector == 'default' || $css_price_selector == '') {
469
            $css_price_selector = $this->defaultConfigs['PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'];
470
        } elseif (!unserialize($css_price_selector)) { //in the case of a custom string selector, we keep it
471
            $css_price_selector = serialize(array($css_price_selector));
472
        }
473
474
        return $css_price_selector;
475
    }
476
}
477
478
/**
479
 * Add widget Js
480
 **/
481
function add_pagantis_widget_js()
482
{
483
    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

483
    /** @scrutinizer ignore-call */ 
484
    wp_enqueue_script('pgSDK', 'https://cdn.pagantis.com/js/pg-v2/sdk.js', '', '', true);
Loading history...
484
    wp_enqueue_script('pmtSDK', 'https://cdn.pagamastarde.com/js/pmt-v2/sdk.js', '', '', true);
485
}
486
487
$WcPagantis = new WcPagantis();
488