Passed
Pull Request — master (#48)
by
unknown
02:40
created

WC_Pagantis_Plugin   F

Complexity

Total Complexity 96

Size/Duplication

Total Lines 739
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 371
dl 0
loc 739
rs 2
c 0
b 0
f 0
wmc 96

26 Methods

Rating   Name   Duplication   Size   Complexity  
B pagantisAddProductSimulator() 0 44 11
A bootstrap() 0 6 2
A loadPagantisTranslation() 0 7 2
A addProductSimulatorTemplate() 0 13 1
A __wakeup() 0 2 1
A check_dependencies() 0 11 4
A save_pg_promoted_bulk_template() 0 11 2
A pagantis_promoted_bulk_template() 0 3 1
F prepare_wpdb_tables() 0 142 21
A get_plugin_action_links() 0 8 1
A add_pagantis_gateway() 0 10 2
A pagantisPromotedVarSave() 0 7 2
A __construct() 0 29 1
A prepareQuantitySelector() 0 9 4
A enqueue_simulator_scripts() 0 44 4
A get_pagantis_logs() 0 27 5
A get_instance() 0 7 2
A register_pg_rest_routes() 0 25 1
B updateExtraConfig() 0 45 10
A __clone() 0 2 1
A pagantisPromotedProductTpl() 0 10 1
A preparePriceSelector() 0 9 4
A get_plugin_row_meta_links() 0 13 2
A check_if_pg_is_in_available_gateways() 0 8 2
B readApi() 0 34 8
A get_setting_link() 0 5 1

How to fix   Complexity   

Complex Class

Complex classes like WC_Pagantis_Plugin 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 WC_Pagantis_Plugin, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Plugin Name: Pagantis
4
 * Plugin URI: https://developer.pagantis.com/platforms/#woocommerce
5
 * Author: Pagantis
6
 * Author URI: https://www.pagantis.com/
7
 * Description: Adds Pagantis as payment method to WooCommerce.
8
 * Version: 8.3.7
9
 * Requires at least: 5.3
10
 * Requires PHP:      7.2
11
 * Text Domain: pagantis
12
 * Domain Path: /languages
13
 * WC requires at least: 3.0
14
 */
15
16
//namespace Gateways;
17
18
19
if ( ! defined('ABSPATH')) {
20
    exit;
21
}
22
define('PAGANTIS_VERSION', '8.3.7');
23
24
define('PAGANTIS_WC_MAIN_FILE', __FILE__);
25
define('PAGANTIS_PLUGIN_URL',
26
    untrailingslashit(plugins_url(basename(plugin_dir_path(PAGANTIS_WC_MAIN_FILE)), basename(PAGANTIS_WC_MAIN_FILE))));
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

26
    untrailingslashit(plugins_url(basename(/** @scrutinizer ignore-call */ plugin_dir_path(PAGANTIS_WC_MAIN_FILE)), basename(PAGANTIS_WC_MAIN_FILE))));
Loading history...
Bug introduced by
The function untrailingslashit 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

26
    /** @scrutinizer ignore-call */ 
27
    untrailingslashit(plugins_url(basename(plugin_dir_path(PAGANTIS_WC_MAIN_FILE)), basename(PAGANTIS_WC_MAIN_FILE))));
Loading history...
Bug introduced by
The function plugins_url was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

26
    untrailingslashit(/** @scrutinizer ignore-call */ plugins_url(basename(plugin_dir_path(PAGANTIS_WC_MAIN_FILE)), basename(PAGANTIS_WC_MAIN_FILE))));
Loading history...
27
define('PAGANTIS_PLUGIN_PATH', untrailingslashit(plugin_dir_path(PAGANTIS_WC_MAIN_FILE)));
28
define('PAGANTIS_ORDERS_TABLE', 'cart_process');
29
define('PAGANTIS_WC_ORDERS_TABLE', 'posts');
30
define('PAGANTIS_LOGS_TABLE', 'pagantis_logs');
31
define('PAGANTIS_NOT_CONFIRMED_MESSAGE', 'No se ha podido confirmar el pago');
32
define('PAGANTIS_CONFIG_TABLE', 'pagantis_config');
33
define('PAGANTIS_CONCURRENCY_TABLE', 'pagantis_concurrency');
34
define('PAGANTIS_GIT_HUB_URL', 'https://github.com/pagantis/woocommerce');
35
define('PAGANTIS_DOC_URL', 'https://developer.pagantis.com');
36
define('PAGANTIS_SUPPORT_EMAIL', 'mailto:[email protected]?Subject=woocommerce_plugin');
37
define('PAGANTIS_PLUGIN_ID', 'pagantis');
38
39
40
class WC_Pagantis_Plugin
41
{
42
43
44
    /**
45
     * The reference the *Singleton* instance of this class.
46
     *
47
     * @var $instance
0 ignored issues
show
Documentation Bug introduced by
The doc comment $instance at position 0 could not be parsed: Unknown type name '$instance' at position 0 in $instance.
Loading history...
48
     */
49
    private static $instance;
50
51
52
    /**
53
     * @var array $defaultConfig
54
     */
55
    private $initialConfig;
56
57
    /**
58
     * @var array $extraConfig
59
     */
60
    private $extraConfig;
61
62
63
    /**
64
     * WC_Pagantis constructor.
65
     */
66
    public function __construct()
67
    {
68
        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

68
        require_once(/** @scrutinizer ignore-call */ plugin_dir_path(__FILE__) . 'vendor/autoload.php');
Loading history...
69
        require_once dirname(__FILE__) . '/includes/class-wc-pagantis-config.php';
70
        require_once dirname(__FILE__) . '/includes/functions.php';
71
72
        $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...
73
74
        $this->prepare_wpdb_tables();
75
        $this->initialConfig = WC_Pagantis_Config::getDefaultConfig();
76
77
        $this->extraConfig = WC_Pagantis_Config::getExtraConfig();
78
        add_action('plugins_loaded', array($this, 'bootstrap'));
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

78
        /** @scrutinizer ignore-call */ 
79
        add_action('plugins_loaded', array($this, 'bootstrap'));
Loading history...
79
        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

79
        /** @scrutinizer ignore-call */ 
80
        load_plugin_textdomain('pagantis', false, basename(dirname(__FILE__)) . '/languages');
Loading history...
80
        add_filter('woocommerce_payment_gateways', array($this, 'add_pagantis_gateway'));
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

80
        /** @scrutinizer ignore-call */ 
81
        add_filter('woocommerce_payment_gateways', array($this, 'add_pagantis_gateway'));
Loading history...
81
        add_filter('woocommerce_available_payment_gateways', array($this, 'check_if_pg_is_in_available_gateways'),
82
            9999);
83
        add_filter('plugin_row_meta', array($this, 'get_plugin_row_meta_links'), 10, 2);
84
        add_filter('plugin_action_links_' . plugin_basename(__FILE__), array($this, 'get_plugin_action_links'));
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

84
        add_filter('plugin_action_links_' . /** @scrutinizer ignore-call */ plugin_basename(__FILE__), array($this, 'get_plugin_action_links'));
Loading history...
85
86
        add_action('wp_enqueue_scripts', 'add_pagantis_widget_js');
87
        add_action('rest_api_init', array($this, 'register_pg_rest_routes')); //Endpoint
88
        add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
89
        register_activation_hook(__FILE__, array($this, 'prepare_wpdb_tables'));
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

89
        /** @scrutinizer ignore-call */ 
90
        register_activation_hook(__FILE__, array($this, 'prepare_wpdb_tables'));
Loading history...
90
        add_action('woocommerce_product_options_general_product_data', array($this, 'pagantisPromotedProductTpl'));
91
        add_action('woocommerce_process_product_meta', array($this, 'pagantisPromotedVarSave'));
92
        add_action('woocommerce_product_bulk_edit_start', array($this, 'pagantis_promoted_bulk_template'));
93
        add_action('woocommerce_product_bulk_edit_save', array($this, 'save_pg_promoted_bulk_template'));
94
        add_action('woocommerce_after_add_to_cart_form', array($this, 'pagantisAddProductSimulator'));
95
        //add_action('wp_enqueue_scripts', array($this, 'enqueue_simulator_scripts'));
96
    }
97
98
    /**
99
     * Returns the *Singleton* instance of this class.
100
     *
101
     * @return self::$instance The *Singleton* instance.
102
     */
103
    public static function get_instance()
104
    {
105
        if (null === self::$instance) {
106
            self::$instance = new self();
107
        }
108
109
        return self::$instance;
110
    }
111
112
    /**
113
     * Private clone method to prevent cloning of the instance of the
114
     * *Singleton* instance.
115
     *
116
     * @return void
117
     */
118
    private function __clone()
119
    {
120
    }
121
122
    /**
123
     * Private unserialize method to prevent unserializing of the *Singleton*
124
     * instance.
125
     *
126
     * @return void
127
     */
128
    private function __wakeup()
129
    {
130
    }
131
132
    public function bootstrap()
133
    {
134
        try {
135
            $this->check_dependencies();
136
        } catch (Exception $e) {
137
            $e->getMessage();
138
        }
139
    }
140
141
    /**
142
     * @throws Exception
143
     */
144
    public function check_dependencies()
145
    {
146
        if (version_compare(WC()->version, '3.0', '<')) {
0 ignored issues
show
Bug introduced by
The function WC was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

146
        if (version_compare(/** @scrutinizer ignore-call */ WC()->version, '3.0', '<')) {
Loading history...
147
            throw new Exception(__('Pagantis requires WooCommerce version 3.0 or greater', 'pagantis'));
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

147
            throw new Exception(/** @scrutinizer ignore-call */ __('Pagantis requires WooCommerce version 3.0 or greater', 'pagantis'));
Loading history...
148
        }
149
150
        if ( ! function_exists('curl_init')) {
151
            throw new Exception(__('Pagantis requires cURL to be installed on your server', 'pagantis'));
152
        }
153
        if ( ! version_compare(phpversion(), '5.3.0', '>=')) {
154
            throw new Exception(__('Pagantis requires PHP 5.3 or greater to be installed on your server', 'pagantis'));
155
        }
156
    }
157
158
    /**
159
     * Piece of html code to insert into BULK admin edit
160
     */
161
    public function pagantis_promoted_bulk_template()
162
    {
163
        echo '<div class="inline-edit-group">
164
			<label class="alignleft">
165
				<span class="title">Pagantis promoted</span>
166
				<span class="input-text-wrap">
167
                    <input type="checkbox" id="pagantis_promoted" name="pagantis_promoted"/>
168
				</span>
169
			</label>
170
		</div>';
171
    }
172
173
    /**
174
     * Php code to save our meta after a bulk admin edit
175
     *
176
     * @param $product
177
     */
178
    public function save_pg_promoted_bulk_template($product)
179
    {
180
        $post_id                 = $product->get_id();
181
        $pagantis_promoted_value = $_REQUEST['pagantis_promoted'];
182
        if ($pagantis_promoted_value === 'on') {
183
            $pagantis_promoted_value = 'yes';
184
        } else {
185
            $pagantis_promoted_value = 'no';
186
        }
187
188
        update_post_meta($post_id, 'custom_product_pagantis_promoted', esc_attr($pagantis_promoted_value));
0 ignored issues
show
Bug introduced by
The function esc_attr 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
        update_post_meta($post_id, 'custom_product_pagantis_promoted', /** @scrutinizer ignore-call */ esc_attr($pagantis_promoted_value));
Loading history...
Bug introduced by
The function update_post_meta 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_post_meta($post_id, 'custom_product_pagantis_promoted', esc_attr($pagantis_promoted_value));
Loading history...
189
    }
190
191
    /**
192
     * Piece of html code to insert into PRODUCT admin edit
193
     */
194
    public function pagantisPromotedProductTpl()
195
    {
196
        global $post;
197
        $_product = get_post_meta($post->ID);
0 ignored issues
show
Bug introduced by
The function get_post_meta 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

197
        $_product = /** @scrutinizer ignore-call */ get_post_meta($post->ID);
Loading history...
198
        woocommerce_wp_checkbox(array(
0 ignored issues
show
Bug introduced by
The function woocommerce_wp_checkbox 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
        /** @scrutinizer ignore-call */ 
199
        woocommerce_wp_checkbox(array(
Loading history...
199
            'id'      => 'pagantis_promoted',
200
            'label'   => __('Pagantis promoted', 'woocommerce'), // phpcs:ignore WordPress.WP.I18n.TextDomainMismatch
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

200
            'label'   => /** @scrutinizer ignore-call */ __('Pagantis promoted', 'woocommerce'), // phpcs:ignore WordPress.WP.I18n.TextDomainMismatch
Loading history...
201
            'value'   => $_product['custom_product_pagantis_promoted']['0'],
202
            'cbvalue' => 'yes',
203
            'echo'    => true,
204
        ));
205
    }
206
207
    /**
208
     *  Php code to save our meta after a PRODUCT admin edit
209
     *
210
     * @param $post_id
211
     */
212
    public function pagantisPromotedVarSave($post_id)
213
    {
214
        $pagantis_promoted_value = $_POST['pagantis_promoted'];
215
        if ($pagantis_promoted_value === null) {
216
            $pagantis_promoted_value = 'no';
217
        }
218
        update_post_meta($post_id, 'custom_product_pagantis_promoted', esc_attr($pagantis_promoted_value));
0 ignored issues
show
Bug introduced by
The function esc_attr 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
        update_post_meta($post_id, 'custom_product_pagantis_promoted', /** @scrutinizer ignore-call */ esc_attr($pagantis_promoted_value));
Loading history...
Bug introduced by
The function update_post_meta 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
        update_post_meta($post_id, 'custom_product_pagantis_promoted', esc_attr($pagantis_promoted_value));
Loading history...
219
    }
220
221
    /*
222
     * Replace 'textdomain' with your plugin's textdomain. e.g. 'woocommerce'.
223
     * File to be named, for example, yourtranslationfile-en_GB.mo
224
     * File to be placed, for example, wp-content/languages/textdomain/yourtranslationfile-en_GB.mo
225
     */
226
    public function loadPagantisTranslation($mofile, $domain)
227
    {
228
        if ('pagantis' === $domain) {
229
            $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

229
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . /** @scrutinizer ignore-call */ get_locale() . '.mo';
Loading history...
230
        }
231
232
        return $mofile;
233
    }
234
235
    /**
236
     * Sql table
237
     */
238
    public function prepare_wpdb_tables()
239
    {
240
        global $wpdb;
241
242
        $tableName = $wpdb->prefix . PAGANTIS_CONCURRENCY_TABLE;
243
        if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") !== $tableName) {
244
            $charset_collate = $wpdb->get_charset_collate();
245
            $sql             = "CREATE TABLE $tableName ( order_id int NOT NULL,  
246
                    createdAt timestamp DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY id (order_id)) $charset_collate";
247
            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...
248
            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

248
            /** @scrutinizer ignore-call */ 
249
            dbDelta($sql);
Loading history...
249
        }
250
251
        $tableName = $wpdb->prefix . PAGANTIS_CONFIG_TABLE;
252
253
        //Check if table exists
254
        $tableExists = $wpdb->get_var("SHOW TABLES LIKE '$tableName'") !== $tableName;
255
        if ($tableExists) {
256
            $charset_collate = $wpdb->get_charset_collate();
257
            $sql             = "CREATE TABLE IF NOT EXISTS $tableName (
258
                                id int NOT NULL AUTO_INCREMENT, 
259
                                config varchar(60) NOT NULL, 
260
                                value varchar(1000) NOT NULL, 
261
                                UNIQUE KEY id(id)) $charset_collate";
262
263
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
264
            dbDelta($sql);
265
        } else {
266
            //Updated value field to adapt to new length < v8.0.1
267
            $query   =
268
                "select COLUMN_TYPE FROM information_schema.COLUMNS where TABLE_NAME='$tableName' AND COLUMN_NAME='value'";
269
            $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...
270
            if ($results['0']['COLUMN_TYPE'] === 'varchar(100)') {
271
                $sql = "ALTER TABLE $tableName MODIFY value varchar(1000)";
272
                $wpdb->query($sql);
273
            }
274
275
            //Adapting selector to array < v8.1.1
276
            $query           = "select * from $tableName where config='PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR' 
277
                               or config='PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'";
278
            $dbCurrentConfig = $wpdb->get_results($query, ARRAY_A);
279
            foreach ($dbCurrentConfig as $item) {
280
                if ($item['config'] === 'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR') {
281
                    $css_price_selector = $this->preparePriceSelector($item['value']);
282
                    if ($item['value'] !== $css_price_selector) {
283
                        $wpdb->update($tableName, array('value' => stripslashes($css_price_selector)),
284
                            array('config' => 'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'), array('%s'), array('%s'));
285
                    }
286
                } elseif ($item['config'] === 'PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR') {
287
                    $css_quantity_selector = $this->prepareQuantitySelector($item['value']);
288
                    if ($item['value'] !== $css_quantity_selector) {
289
                        $wpdb->update($tableName, array('value' => stripslashes($css_quantity_selector)),
290
                            array('config' => 'PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'), array('%s'), array('%s'));
291
                    }
292
                }
293
            }
294
        }
295
296
        //Adapting selector to array < v8.2.2
297
        $tableName = $wpdb->prefix . PAGANTIS_CONFIG_TABLE;
298
        $query     = "select * from $tableName where config='PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'";
299
        $results   = $wpdb->get_results($query, ARRAY_A);
300
        if (count($results) === 0) {
301
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR', 'value' => '.'),
302
                array('%s', '%s'));
303
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR', 'value' => ','),
304
                array('%s', '%s'));
305
        }
306
307
        //Adding new selector < v8.3.0
308
        $tableName = $wpdb->prefix . PAGANTIS_CONFIG_TABLE;
309
        $query     = "select * from $tableName where config='PAGANTIS_DISPLAY_MAX_AMOUNT'";
310
        $results   = $wpdb->get_results($query, ARRAY_A);
311
        if (count($results) === 0) {
312
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_DISPLAY_MAX_AMOUNT', 'value' => '0'),
313
                array('%s', '%s'));
314
        }
315
316
        //Adding new selector < v8.3.2
317
        $tableName = $wpdb->prefix . PAGANTIS_CONFIG_TABLE;
318
        $query     = "select * from $tableName where config='PAGANTIS_SIMULATOR_DISPLAY_SITUATION'";
319
        $results   = $wpdb->get_results($query, ARRAY_A);
320
        if (count($results) === 0) {
321
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_SIMULATOR_DISPLAY_SITUATION', 'value' => 'default'),
322
                array('%s', '%s'));
323
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_SIMULATOR_SELECTOR_VARIATION', 'value' => 'default'),
324
                array('%s', '%s'));
325
        }
326
327
        //Adding new selector < v8.3.3
328
        $tableName = $wpdb->prefix . PAGANTIS_CONFIG_TABLE;
329
        $query     = "select * from $tableName where config='PAGANTIS_SIMULATOR_DISPLAY_TYPE_CHECKOUT'";
330
        $results   = $wpdb->get_results($query, ARRAY_A);
331
        if (count($results) === 0) {
332
            $wpdb->insert($tableName, array(
333
                'config' => 'PAGANTIS_SIMULATOR_DISPLAY_TYPE_CHECKOUT',
334
                'value'  => 'sdk.simulator.types.CHECKOUT_PAGE',
335
            ), array('%s', '%s'));
336
            $wpdb->update($tableName, array('value' => 'sdk.simulator.types.PRODUCT_PAGE'),
337
                array('config' => 'PAGANTIS_SIMULATOR_DISPLAY_TYPE'), array('%s'), array('%s'));
338
        }
339
340
        //Adapting to variable selector < v8.3.6
341
        $variableSelector =
342
            'div.summary div.woocommerce-variation.single_variation > div.woocommerce-variation-price span.price';
343
        $tableName        = $wpdb->prefix . PAGANTIS_CONFIG_TABLE;
344
        $query            =
345
            "select * from $tableName where config='PAGANTIS_SIMULATOR_SELECTOR_VARIATION' and value='default'";
346
        $results          = $wpdb->get_results($query, ARRAY_A);
347
        if (count($results) === 0) {
348
            $wpdb->update($tableName, array('value' => $variableSelector),
349
                array('config' => 'PAGANTIS_SIMULATOR_SELECTOR_VARIATION'), array('%s'), array('%s'));
350
        }
351
352
        $dbConfigs = $wpdb->get_results("select * from $tableName", ARRAY_A);
353
354
        // Convert a multiple dimension array for SQL insert statements into a simple key/value
355
        $simpleDbConfigs = array();
356
        foreach ($dbConfigs as $config) {
357
            $simpleDbConfigs[$config['config']] = $config['value'];
358
        }
359
        $newConfigs = array_diff_key(WC_Pagantis_Config::getDefaultConfig(), $simpleDbConfigs);
360
        if ( ! empty($newConfigs)) {
361
            foreach ($newConfigs as $key => $value) {
362
                $wpdb->insert($tableName, array('config' => $key, 'value' => $value), array('%s', '%s'));
363
            }
364
        }
365
366
        //Current plugin config: pagantis_public_key => New field --- public_key => Old field
367
        $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

367
        $settings = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
368
369
        if ( ! isset($settings['pagantis_public_key']) && $settings['public_key']) {
370
            $settings['pagantis_public_key'] = $settings['public_key'];
371
            unset($settings['public_key']);
372
        }
373
374
        if ( ! isset($settings['pagantis_private_key']) && $settings['secret_key']) {
375
            $settings['pagantis_private_key'] = $settings['secret_key'];
376
            unset($settings['secret_key']);
377
        }
378
379
        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

379
        /** @scrutinizer ignore-call */ 
380
        update_option('woocommerce_pagantis_settings', $settings);
Loading history...
380
    }
381
382
383
    public function enqueue_simulator_scripts()
384
    {
385
        if ( ! pg_isPluginActive()) {
386
            return;
387
        }
388
389
        wp_register_script('pagantis-simulator', plugins_url('assets/js/pagantis-simulator.js', PAGANTIS_PLUGIN_ID),
0 ignored issues
show
Bug introduced by
The function plugins_url was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

389
        wp_register_script('pagantis-simulator', /** @scrutinizer ignore-call */ plugins_url('assets/js/pagantis-simulator.js', PAGANTIS_PLUGIN_ID),
Loading history...
Bug introduced by
The function wp_register_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

389
        /** @scrutinizer ignore-call */ 
390
        wp_register_script('pagantis-simulator', plugins_url('assets/js/pagantis-simulator.js', PAGANTIS_PLUGIN_ID),
Loading history...
390
            array('jquery'), '');
391
        wp_enqueue_script('pagantis-simulator');
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

391
        /** @scrutinizer ignore-call */ 
392
        wp_enqueue_script('pagantis-simulator');
Loading history...
392
393
        global $product;
394
395
        pg_canProductSimulatorLoad();
396
        $locale   = pg_GetLocaleString();
397
        $settings = pg_get_plugin_settings();
398
399
        $post_id                    = $product->get_id();
400
        $simulator_localized_params = array(
401
            'total'                     => is_numeric($product->get_price()) ? $product->get_price() : 0,
402
            'public_key'                => $settings['pagantis_public_key'],
403
            'simulator_type'            => WC_Pagantis_Config::getValueOfKey('PAGANTIS_SIMULATOR_DISPLAY_TYPE'),
404
            'positionSelector'          => WC_Pagantis_Config::getValueOfKey('PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'),
405
            'quantitySelector'          => WC_Pagantis_Config::getValueOfKey('PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR',
406
                true),
407
            'priceSelector'             => WC_Pagantis_Config::getValueOfKey('PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR',
408
                true),
409
            'totalAmount'               => is_numeric($product->get_price()) ? $product->get_price() : 0,
410
            'locale'                    => $locale,
411
            'country'                   => $locale,
412
            'isProductPromoted'         => pg_isProductPromoted($post_id),
413
            'promotedMessage'           => WC_Pagantis_Config::getValueOfKey('PAGANTIS_PROMOTION_EXTRA'),
414
            'thousandSeparator'         => WC_Pagantis_Config::getValueOfKey('PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'),
415
            'decimalSeparator'          => WC_Pagantis_Config::getValueOfKey('PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR'),
416
            'pagantisQuotesStart'       => WC_Pagantis_Config::getValueOfKey('PAGANTIS_SIMULATOR_START_INSTALLMENTS'),
417
            'pagantisSimulatorSkin'     => WC_Pagantis_Config::getValueOfKey('PAGANTIS_SIMULATOR_DISPLAY_SKIN'),
418
            'pagantisSimulatorPosition' => WC_Pagantis_Config::getValueOfKey('PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION'),
419
            'finalDestination'          => WC_Pagantis_Config::getValueOfKey('PAGANTIS_SIMULATOR_DISPLAY_SITUATION'),
420
            'variationSelector'         => WC_Pagantis_Config::getValueOfKey('PAGANTIS_SIMULATOR_SELECTOR_VARIATION'),
421
            'productType'               => $product->get_type(),
422
        );
423
424
        wp_localize_script('pagantis-simulator', 'pg_sim_params', $simulator_localized_params);
0 ignored issues
show
Bug introduced by
The function wp_localize_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

424
        /** @scrutinizer ignore-call */ 
425
        wp_localize_script('pagantis-simulator', 'pg_sim_params', $simulator_localized_params);
Loading history...
425
426
        wp_enqueue_script('pg_sim_params');
427
    }
428
429
430
    /**
431
     * Product simulator
432
     */
433
    public function addProductSimulatorTemplate()
434
    {
435
        global $product;
436
437
        pg_canProductSimulatorLoad();
438
439
        $post_id            = $product->get_id();
440
        $template_arguments = array(
441
            'isProductPromoted' => pg_isProductPromoted($post_id),
442
            'promotedMessage'   => WC_Pagantis_Config::getValueOfKey('PAGANTIS_PROMOTION_EXTRA'),
443
        );
444
445
        wc_get_template('product_simulator.php', $template_arguments, '', $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

445
        /** @scrutinizer ignore-call */ 
446
        wc_get_template('product_simulator.php', $template_arguments, '', $this->template_path);
Loading history...
446
    }
447
448
    /**
449
     * Product simulator
450
     *
451
     * @global WC_Product $product Product object.
452
     */
453
    public function pagantisAddProductSimulator()
454
    {
455
        global $product;
456
457
        $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

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

458
        $locale           = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
459
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
460
        $allowedCountry   = (in_array(strtolower($locale), $allowedCountries));
461
        $minAmount        = $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'];
462
        $maxAmount        = $this->extraConfig['PAGANTIS_DISPLAY_MAX_AMOUNT'];
463
        $totalPrice       = $product->get_price();
464
        $validAmount      = ($totalPrice >= $minAmount && ($totalPrice <= $maxAmount || $maxAmount === '0'));
465
        if ($cfg['enabled'] !== 'yes' || $cfg['pagantis_public_key'] === '' || $cfg['pagantis_private_key'] === ''
466
            || $cfg['simulator'] !== 'yes'
467
            || ! $allowedCountry
468
            || ! $validAmount
469
        ) {
470
            return;
471
        }
472
473
        $post_id         = $product->get_id();
474
        $template_fields = array(
475
            'total'                     => is_numeric($product->get_price()) ? $product->get_price() : 0,
476
            'public_key'                => $cfg['pagantis_public_key'],
477
            'simulator_type'            => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE'],
478
            'positionSelector'          => $this->extraConfig['PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'],
479
            'quantitySelector'          => unserialize($this->extraConfig['PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR']),
480
            'priceSelector'             => unserialize($this->extraConfig['PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR']),
481
            'totalAmount'               => is_numeric($product->get_price()) ? $product->get_price() : 0,
482
            'locale'                    => $locale,
483
            'country'                   => $locale,
484
            'promoted'                  => pg_isProductPromoted($post_id),
485
            'promotedMessage'           => $this->extraConfig['PAGANTIS_PROMOTION_EXTRA'],
486
            'thousandSeparator'         => $this->extraConfig['PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'],
487
            'decimalSeparator'          => $this->extraConfig['PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR'],
488
            'pagantisQuotesStart'       => $this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS'],
489
            'pagantisSimulatorSkin'     => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_SKIN'],
490
            'pagantisSimulatorPosition' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION'],
491
            'finalDestination'          => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_SITUATION'],
492
            'variationSelector'         => $this->extraConfig['PAGANTIS_SIMULATOR_SELECTOR_VARIATION'],
493
            'productType'               => $product->get_type(),
494
        );
495
        WC_Pagantis_Logger::insert_log_entry_in_wpdb($template_fields);
496
        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

496
        /** @scrutinizer ignore-call */ 
497
        wc_get_template('product_simulator.php', $template_fields, '', $this->template_path);
Loading history...
497
    }
498
499
500
    /**
501
     * Add Pagantis to payments list.
502
     *
503
     * @param $methods
504
     *
505
     * @return array
506
     * @hook woocommerce_payment_gateways
507
     */
508
    public function add_pagantis_gateway($methods)
509
    {
510
        if ( ! class_exists('WC_Payment_Gateway')) {
511
            return $methods;
512
        }
513
514
        include_once('controllers/class-wc-pagantis-gateway.php');
515
        $methods[] = 'WC_Pagantis_Gateway';
516
517
        return $methods;
518
    }
519
520
    /**
521
     * Initialize WC_Pagantis class
522
     *
523
     * @param $methods
524
     *
525
     * @return mixed
526
     */
527
    public function check_if_pg_is_in_available_gateways($methods)
528
    {
529
        $pagantis = new WC_Pagantis_Gateway();
530
        if ( ! $pagantis->is_available()) {
531
            unset($methods['pagantis']);
532
        }
533
534
        return $methods;
535
    }
536
537
    /**
538
     * Add links to Plugin description in WP Plugins panel
539
     *
540
     * @param $links
541
     *
542
     * @return mixed
543
     * @hook plugin_action_links_pagantis
544
     */
545
    public function get_plugin_action_links($links)
546
    {
547
        $setting_link = $this->get_setting_link();
548
        $plugin_links = array(
549
            '<a href="' . $setting_link . '">' . __('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

549
            '<a href="' . $setting_link . '">' . /** @scrutinizer ignore-call */ __('Settings', 'pagantis') . '</a>',
Loading history...
550
        );
551
552
        return array_merge($plugin_links, $links);
553
    }
554
555
556
    public function get_setting_link()
557
    {
558
        $section_slug = 'pagantis';
559
560
        return admin_url('admin.php?page=wc-settings&tab=checkout&section=' . $section_slug);
0 ignored issues
show
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

560
        return /** @scrutinizer ignore-call */ admin_url('admin.php?page=wc-settings&tab=checkout&section=' . $section_slug);
Loading history...
561
    }
562
563
    /**
564
     * Add links to Plugin options
565
     *
566
     * @param $links
567
     * @param $file
568
     *
569
     * @hook plugin_row_meta
570
     * @return array
571
     */
572
    public function get_plugin_row_meta_links($links, $file)
573
    {
574
        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

574
        if ($file === /** @scrutinizer ignore-call */ plugin_basename(__FILE__)) {
Loading history...
575
            $links[] =
576
                '<a href="' . PAGANTIS_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

576
                '<a href="' . PAGANTIS_GIT_HUB_URL . '" target="_blank">' . /** @scrutinizer ignore-call */ __('Documentation', 'pagantis') . '</a>';
Loading history...
577
            $links[] =
578
                '<a href="' . PAGANTIS_DOC_URL . '" target="_blank">' . __('API documentation', 'pagantis') . '</a>';
579
            $links[] = '<a href="' . PAGANTIS_SUPPORT_EMAIL . '">' . __('Support', 'pagantis') . '</a>';
580
581
            return $links;
582
        }
583
584
        return $links;
585
    }
586
587
    /**
588
     * Read logs
589
     *
590
     * @param       $data
591
     *
592
     * @global wpdb $wpdb WordPress database abstraction object.
593
     */
594
    public function get_pagantis_logs($data)
595
    {
596
        global $wpdb;
597
        $filters    = ($data->get_params());
598
        $response   = array();
599
        $secretKey  = $filters['secret'];
600
        $from       = $filters['from'];
601
        $to         = $filters['to'];
602
        $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

602
        $cfg        = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
603
        $privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
604
        $tableName  = $wpdb->prefix . PAGANTIS_LOGS_TABLE;
605
        $query      = "SELECT * FROM $tableName WHERE createdAt>$from AND createdAt<$to ORDER BY createdAt DESC";
606
        $results    = $wpdb->get_results($query);
607
        if (isset($results) && $privateKey === $secretKey) {
608
            foreach ($results as $key => $result) {
609
                $response[$key]['timestamp'] = $result->createdAt;
610
                $response[$key]['log']       = json_decode($result->log);
611
            }
612
        } else {
613
            $response['result'] = 'Error';
614
        }
615
        $response = json_encode($response);
616
        header('HTTP/1.1 200', true, 200);
617
        header('Content-Type: application/json', true);
618
        header('Content-Length: ' . strlen($response));
619
        echo($response);
620
        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...
621
    }
622
623
    /**
624
     * Update extra config
625
     *
626
     * @param $data
627
     */
628
    public function updateExtraConfig($data)
629
    {
630
        global $wpdb;
631
        $tableName = $wpdb->prefix . PAGANTIS_CONFIG_TABLE;
632
        $response  = array('status' => null);
633
634
        $filters    = ($data->get_params());
635
        $secretKey  = $filters['secret'];
636
        $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

636
        $cfg        = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
637
        $privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
638
        if ($privateKey !== $secretKey) {
639
            $response['status'] = 401;
640
            $response['result'] = 'Unauthorized';
641
        } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
642
            if (count($_POST)) {
643
                foreach ($_POST as $config => $value) {
644
                    if (isset($this->initialConfig[$config]) && $response['status'] === null) {
645
                        $wpdb->update($tableName, array('value' => stripslashes($value)), array('config' => $config),
646
                            array('%s'), array('%s'));
647
                    } else {
648
                        $response['status'] = 400;
649
                        $response['result'] = 'Bad request';
650
                    }
651
                }
652
            } else {
653
                $response['status'] = 422;
654
                $response['result'] = 'Empty data';
655
            }
656
        }
657
658
        if ($response['status'] === null) {
659
            $tableName = $wpdb->prefix . PAGANTIS_CONFIG_TABLE;
660
            $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...
661
            foreach ($dbResult as $value) {
662
                $formattedResult[$value['config']] = $value['value'];
663
            }
664
            $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 661. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
665
        }
666
667
        $result = json_encode($response['result']);
668
        header('HTTP/1.1 ' . $response['status'], true, $response['status']);
669
        header('Content-Type: application/json', true);
670
        header('Content-Length: ' . strlen($result));
671
        echo($result);
672
        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...
673
    }
674
675
    /**
676
     * Read logs
677
     *
678
     * @param $data
679
     */
680
    public function readApi($data)
681
    {
682
        global $wpdb;
683
        $filters        = ($data->get_params());
684
        $response       = array('timestamp' => time());
685
        $secretKey      = $filters['secret'];
686
        $from           = ($filters['from']) ? date_create($filters['from']) : date('Y-m-d', strtotime('-7 day'));
687
        $to             = ($filters['to']) ? date_create($filters['to']) : date('Y-m-d', strtotime('+1 day'));
688
        $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...
689
        $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

689
        $cfg            = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
690
        $privateKey     = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
691
        $tableName      = $wpdb->prefix . PAGANTIS_WC_ORDERS_TABLE;
692
        $tableNameInner = $wpdb->prefix . 'postmeta';
693
        $query          = "SELECT * FROM $tableName tn INNER JOIN $tableNameInner tn2 ON tn2.post_id = tn.id
694
                  WHERE tn.post_type='shop_order' AND tn.post_date>'" . $from->format('Y-m-d') . "' 
695
                  AND tn.post_date<'" . $to->format('Y-m-d') . "' ORDER BY tn.post_date DESC";
696
        $results        = $wpdb->get_results($query);
697
698
        if (isset($results) && $privateKey === $secretKey) {
699
            foreach ($results as $result) {
700
                $key                                          = $result->ID;
701
                $response['message'][$key]['timestamp']       = $result->post_date;
702
                $response['message'][$key]['order_id']        = $key;
703
                $response['message'][$key][$result->meta_key] = $result->meta_value;
704
            }
705
        } else {
706
            $response['result'] = 'Error';
707
        }
708
        $response = json_encode($response);
709
        header('HTTP/1.1 200', true, 200);
710
        header('Content-Type: application/json', true);
711
        header('Content-Length: ' . strlen($response));
712
        echo($response);
713
        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...
714
    }
715
716
    /**
717
     * ENDPOINT - Read logs -> Hook: rest_api_init
718
     *
719
     * @hook rest_api_init
720
     * @return mixed
721
     */
722
    public function register_pg_rest_routes()
723
    {
724
        register_rest_route('pagantis/v1', '/logs/(?P<secret>\w+)/(?P<from>\d+)/(?P<to>\d+)', array(
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

724
        /** @scrutinizer ignore-call */ 
725
        register_rest_route('pagantis/v1', '/logs/(?P<secret>\w+)/(?P<from>\d+)/(?P<to>\d+)', array(
Loading history...
725
            'methods'  => 'GET',
726
            'callback' => array(
727
                $this,
728
                'get_pagantis_logs',
729
            ),
730
        ), true);
731
732
        register_rest_route('pagantis/v1', '/configController/(?P<secret>\w+)', array(
733
            'methods'  => 'GET, POST',
734
            'callback' => array(
735
                $this,
736
                'updateExtraConfig',
737
            ),
738
        ), true);
739
740
        register_rest_route('pagantis/v1', '/api/(?P<secret>\w+)/(?P<from>\w+)/(?P<to>\w+)', array(
741
            'methods'  => 'GET',
742
            'callback' => array(
743
                $this,
744
                'readApi',
745
            ),
746
        ), true);
747
    }
748
749
    /**
750
     * @param $css_quantity_selector
751
     *
752
     * @return mixed|string
753
     */
754
    private function prepareQuantitySelector($css_quantity_selector)
755
    {
756
        if ($css_quantity_selector === 'default' || $css_quantity_selector === '') {
757
            $css_quantity_selector = $this->initialConfig['PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'];
758
        } elseif ( ! unserialize($css_quantity_selector)) { //in the case of a custom string selector, we keep it
759
            $css_quantity_selector = serialize(array($css_quantity_selector));
760
        }
761
762
        return $css_quantity_selector;
763
    }
764
765
    /**
766
     * @param $css_price_selector
767
     *
768
     * @return mixed|string
769
     */
770
    private function preparePriceSelector($css_price_selector)
771
    {
772
        if ($css_price_selector === 'default' || $css_price_selector === '') {
773
            $css_price_selector = $this->initialConfig['PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'];
774
        } elseif ( ! unserialize($css_price_selector)) { //in the case of a custom string selector, we keep it
775
            $css_price_selector = serialize(array($css_price_selector));
776
        }
777
778
        return $css_price_selector;
779
    }
780
}
781
782
/**
783
 * Add widget Js
784
 **/
785
function add_pagantis_widget_js()
786
{
787
    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

787
    /** @scrutinizer ignore-call */ 
788
    wp_enqueue_script('pgSDK', 'https://cdn.pagantis.com/js/pg-v2/sdk.js', '', '', true);
Loading history...
788
}
789
790
WC_Pagantis_Plugin::get_instance();
791
792
/**
793
 * Main instance WC_Pagantis_Plugin.
794
 *
795
 * Returns the main instance of WC_Pagantis_Plugin.
796
 *
797
 * @return WC_Pagantis_Plugin
798
 */
799
function PG_WC() // phpcs:ignore
800
{
801
    return WC_Pagantis_Plugin::get_instance();
802
}
803