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

WC_Pagantis_Plugin::add_pagantis_gateway()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 10
rs 10
c 0
b 0
f 0
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(
26
    'PAGANTIS_PLUGIN_URL',
27
    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

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

27
    untrailingslashit(/** @scrutinizer ignore-call */ plugins_url(basename(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

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

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

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

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

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

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

90
        /** @scrutinizer ignore-call */ 
91
        register_activation_hook(__FILE__, array($this, 'prepare_wpdb_tables'));
Loading history...
91
        add_action('woocommerce_product_options_general_product_data', array($this, 'pagantisPromotedProductTpl'));
92
        add_action('woocommerce_process_product_meta', array($this, 'pagantisPromotedVarSave'));
93
        add_action('woocommerce_product_bulk_edit_start', array($this, 'pagantis_promoted_bulk_template'));
94
        add_action('woocommerce_product_bulk_edit_save', array($this, 'save_pg_promoted_bulk_template'));
95
        add_action('woocommerce_after_add_to_cart_form', array($this, 'pagantisAddProductSimulator'));
96
        //add_action('wp_enqueue_scripts', array($this, 'enqueue_simulator_scripts'));
97
    }
98
99
    /**
100
     * Returns the *Singleton* instance of this class.
101
     *
102
     * @return self::$instance The *Singleton* instance.
103
     */
104
    public static function get_instance()
105
    {
106
        if (null === self::$instance) {
107
            self::$instance = new self();
108
        }
109
110
        return self::$instance;
111
    }
112
113
    /**
114
     * Private clone method to prevent cloning of the instance of the
115
     * *Singleton* instance.
116
     *
117
     * @return void
118
     */
119
    private function __clone()
120
    {
121
    }
122
123
    /**
124
     * Private unserialize method to prevent unserializing of the *Singleton*
125
     * instance.
126
     *
127
     * @return void
128
     */
129
    private function __wakeup()
130
    {
131
    }
132
133
    public function bootstrap()
134
    {
135
        try {
136
            $this->check_dependencies();
137
        } catch (Exception $e) {
138
            $e->getMessage();
139
        }
140
    }
141
142
    /**
143
     * @throws Exception
144
     */
145
    public function check_dependencies()
146
    {
147
        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

147
        if (version_compare(/** @scrutinizer ignore-call */ WC()->version, '3.0', '<')) {
Loading history...
148
            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

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

189
        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

189
        /** @scrutinizer ignore-call */ 
190
        update_post_meta($post_id, 'custom_product_pagantis_promoted', esc_attr($pagantis_promoted_value));
Loading history...
190
    }
191
192
    /**
193
     * Piece of html code to insert into PRODUCT admin edit
194
     */
195
    public function pagantisPromotedProductTpl()
196
    {
197
        global $post;
198
        $_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

198
        $_product = /** @scrutinizer ignore-call */ get_post_meta($post->ID);
Loading history...
199
        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

199
        /** @scrutinizer ignore-call */ 
200
        woocommerce_wp_checkbox(array(
Loading history...
200
            'id'      => 'pagantis_promoted',
201
            '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

201
            'label'   => /** @scrutinizer ignore-call */ __('Pagantis promoted', 'woocommerce'), // phpcs:ignore WordPress.WP.I18n.TextDomainMismatch
Loading history...
202
            'value'   => $_product['custom_product_pagantis_promoted']['0'],
203
            'cbvalue' => 'yes',
204
            'echo'    => true,
205
        ));
206
    }
207
208
    /**
209
     *  Php code to save our meta after a PRODUCT admin edit
210
     *
211
     * @param $post_id
212
     */
213
    public function pagantisPromotedVarSave($post_id)
214
    {
215
        $pagantis_promoted_value = $_POST['pagantis_promoted'];
216
        if ($pagantis_promoted_value === null) {
217
            $pagantis_promoted_value = 'no';
218
        }
219
        update_post_meta($post_id, 'custom_product_pagantis_promoted', esc_attr($pagantis_promoted_value));
0 ignored issues
show
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

219
        /** @scrutinizer ignore-call */ 
220
        update_post_meta($post_id, 'custom_product_pagantis_promoted', esc_attr($pagantis_promoted_value));
Loading history...
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

219
        update_post_meta($post_id, 'custom_product_pagantis_promoted', /** @scrutinizer ignore-call */ esc_attr($pagantis_promoted_value));
Loading history...
220
    }
221
222
    /*
223
     * Replace 'textdomain' with your plugin's textdomain. e.g. 'woocommerce'.
224
     * File to be named, for example, yourtranslationfile-en_GB.mo
225
     * File to be placed, for example, wp-content/languages/textdomain/yourtranslationfile-en_GB.mo
226
     */
227
    public function loadPagantisTranslation($mofile, $domain)
228
    {
229
        if ('pagantis' === $domain) {
230
            $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

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

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

396
        $settings = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
397
398
        if (! isset($settings['pagantis_public_key']) && $settings['public_key']) {
399
            $settings['pagantis_public_key'] = $settings['public_key'];
400
            unset($settings['public_key']);
401
        }
402
403
        if (! isset($settings['pagantis_private_key']) && $settings['secret_key']) {
404
            $settings['pagantis_private_key'] = $settings['secret_key'];
405
            unset($settings['secret_key']);
406
        }
407
408
        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

408
        /** @scrutinizer ignore-call */ 
409
        update_option('woocommerce_pagantis_settings', $settings);
Loading history...
409
    }
410
411
412
    public function enqueue_simulator_scripts()
413
    {
414
        if (! pg_isPluginActive()) {
415
            return;
416
        }
417
418
        wp_register_script(
0 ignored issues
show
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

418
        /** @scrutinizer ignore-call */ 
419
        wp_register_script(
Loading history...
419
            'pagantis-simulator',
420
            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

420
            /** @scrutinizer ignore-call */ 
421
            plugins_url('assets/js/pagantis-simulator.js', PAGANTIS_PLUGIN_ID),
Loading history...
421
            array('jquery'),
422
            ''
423
        );
424
        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

424
        /** @scrutinizer ignore-call */ 
425
        wp_enqueue_script('pagantis-simulator');
Loading history...
425
426
        global $product;
427
428
        pg_canProductSimulatorLoad();
429
        $locale   = pg_GetLocaleString();
430
        $settings = pg_get_plugin_settings();
431
432
        $post_id                    = $product->get_id();
433
        $simulator_localized_params = array(
434
            'total'                     => is_numeric($product->get_price()) ? $product->get_price() : 0,
435
            'public_key'                => $settings['pagantis_public_key'],
436
            'simulator_type'            => WC_Pagantis_Config::getValueOfKey('PAGANTIS_SIMULATOR_DISPLAY_TYPE'),
437
            'positionSelector'          => WC_Pagantis_Config::getValueOfKey('PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'),
438
            'quantitySelector'          => WC_Pagantis_Config::getValueOfKey('PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR', true),
439
            'priceSelector'             => WC_Pagantis_Config::getValueOfKey('PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR', true),
440
            'totalAmount'               => is_numeric($product->get_price()) ? $product->get_price() : 0,
441
            'locale'                    => $locale,
442
            'country'                   => $locale,
443
            'isProductPromoted'         => pg_isProductPromoted($post_id),
444
            'promotedMessage'           => WC_Pagantis_Config::getValueOfKey('PAGANTIS_PROMOTION_EXTRA'),
445
            'thousandSeparator'         => WC_Pagantis_Config::getValueOfKey('PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'),
446
            'decimalSeparator'          => WC_Pagantis_Config::getValueOfKey('PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR'),
447
            'pagantisQuotesStart'       => WC_Pagantis_Config::getValueOfKey('PAGANTIS_SIMULATOR_START_INSTALLMENTS'),
448
            'pagantisSimulatorSkin'     => WC_Pagantis_Config::getValueOfKey('PAGANTIS_SIMULATOR_DISPLAY_SKIN'),
449
            'pagantisSimulatorPosition' => WC_Pagantis_Config::getValueOfKey('PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION'),
450
            'finalDestination'          => WC_Pagantis_Config::getValueOfKey('PAGANTIS_SIMULATOR_DISPLAY_SITUATION'),
451
            'variationSelector'         => WC_Pagantis_Config::getValueOfKey('PAGANTIS_SIMULATOR_SELECTOR_VARIATION'),
452
            'productType'               => $product->get_type(),
453
        );
454
455
        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

455
        /** @scrutinizer ignore-call */ 
456
        wp_localize_script('pagantis-simulator', 'pg_sim_params', $simulator_localized_params);
Loading history...
456
457
        wp_enqueue_script('pg_sim_params');
458
    }
459
460
461
    /**
462
     * Product simulator
463
     */
464
    public function addProductSimulatorTemplate()
465
    {
466
        global $product;
467
468
        pg_canProductSimulatorLoad();
469
470
        $post_id            = $product->get_id();
471
        $template_arguments = array(
472
            'isProductPromoted' => pg_isProductPromoted($post_id),
473
            'promotedMessage'   => WC_Pagantis_Config::getValueOfKey('PAGANTIS_PROMOTION_EXTRA'),
474
        );
475
476
        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

476
        /** @scrutinizer ignore-call */ 
477
        wc_get_template('product_simulator.php', $template_arguments, '', $this->template_path);
Loading history...
477
    }
478
479
    /**
480
     * Product simulator
481
     *
482
     * @global WC_Product $product Product object.
483
     */
484
    public function pagantisAddProductSimulator()
485
    {
486
        global $product;
487
488
        $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

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

489
        $locale           = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
490
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
491
        $allowedCountry   = (in_array(strtolower($locale), $allowedCountries));
492
        $minAmount        = $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'];
493
        $maxAmount        = $this->extraConfig['PAGANTIS_DISPLAY_MAX_AMOUNT'];
494
        $totalPrice       = $product->get_price();
495
        $validAmount      = ($totalPrice >= $minAmount && ($totalPrice <= $maxAmount || $maxAmount === '0'));
496
        if ($cfg['enabled'] !== 'yes' || $cfg['pagantis_public_key'] === '' || $cfg['pagantis_private_key'] === ''
497
            || $cfg['simulator'] !== 'yes'
498
            || ! $allowedCountry
499
            || ! $validAmount
500
        ) {
501
            return;
502
        }
503
504
        $post_id         = $product->get_id();
505
        $template_fields = array(
506
            'total'                     => is_numeric($product->get_price()) ? $product->get_price() : 0,
507
            'public_key'                => $cfg['pagantis_public_key'],
508
            'simulator_type'            => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE'],
509
            'positionSelector'          => $this->extraConfig['PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'],
510
            'quantitySelector'          => unserialize($this->extraConfig['PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR']),
511
            'priceSelector'             => unserialize($this->extraConfig['PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR']),
512
            'totalAmount'               => is_numeric($product->get_price()) ? $product->get_price() : 0,
513
            'locale'                    => $locale,
514
            'country'                   => $locale,
515
            'promoted'                  => pg_isProductPromoted($post_id),
516
            'promotedMessage'           => $this->extraConfig['PAGANTIS_PROMOTION_EXTRA'],
517
            'thousandSeparator'         => $this->extraConfig['PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'],
518
            'decimalSeparator'          => $this->extraConfig['PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR'],
519
            'pagantisQuotesStart'       => $this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS'],
520
            'pagantisSimulatorSkin'     => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_SKIN'],
521
            'pagantisSimulatorPosition' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION'],
522
            'finalDestination'          => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_SITUATION'],
523
            'variationSelector'         => $this->extraConfig['PAGANTIS_SIMULATOR_SELECTOR_VARIATION'],
524
            'productType'               => $product->get_type(),
525
        );
526
        WC_Pagantis_Logger::insert_log_entry_in_wpdb($template_fields);
527
        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

527
        /** @scrutinizer ignore-call */ 
528
        wc_get_template('product_simulator.php', $template_fields, '', $this->template_path);
Loading history...
528
    }
529
530
531
    /**
532
     * Add Pagantis to payments list.
533
     *
534
     * @param $methods
535
     *
536
     * @return array
537
     * @hook woocommerce_payment_gateways
538
     */
539
    public function add_pagantis_gateway($methods)
540
    {
541
        if (! class_exists('WC_Payment_Gateway')) {
542
            return $methods;
543
        }
544
545
        include_once('controllers/class-wc-pagantis-gateway.php');
546
        $methods[] = 'WC_Pagantis_Gateway';
547
548
        return $methods;
549
    }
550
551
    /**
552
     * Initialize WC_Pagantis class
553
     *
554
     * @param $methods
555
     *
556
     * @return mixed
557
     */
558
    public function check_if_pg_is_in_available_gateways($methods)
559
    {
560
        $pagantis = new WC_Pagantis_Gateway();
561
        if (! $pagantis->is_available()) {
562
            unset($methods['pagantis']);
563
        }
564
565
        return $methods;
566
    }
567
568
    /**
569
     * Add links to Plugin description in WP Plugins panel
570
     *
571
     * @param $links
572
     *
573
     * @return mixed
574
     * @hook plugin_action_links_pagantis
575
     */
576
    public function get_plugin_action_links($links)
577
    {
578
        $setting_link = $this->get_setting_link();
579
        $plugin_links = array(
580
            '<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

580
            '<a href="' . $setting_link . '">' . /** @scrutinizer ignore-call */ __('Settings', 'pagantis') . '</a>',
Loading history...
581
        );
582
583
        return array_merge($plugin_links, $links);
584
    }
585
586
587
    public function get_setting_link()
588
    {
589
        $section_slug = 'pagantis';
590
591
        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

591
        return /** @scrutinizer ignore-call */ admin_url('admin.php?page=wc-settings&tab=checkout&section=' . $section_slug);
Loading history...
592
    }
593
594
    /**
595
     * Add links to Plugin options
596
     *
597
     * @param $links
598
     * @param $file
599
     *
600
     * @hook plugin_row_meta
601
     * @return array
602
     */
603
    public function get_plugin_row_meta_links($links, $file)
604
    {
605
        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

605
        if ($file === /** @scrutinizer ignore-call */ plugin_basename(__FILE__)) {
Loading history...
606
            $links[] = '<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

606
            $links[] = '<a href="' . PAGANTIS_GIT_HUB_URL . '" target="_blank">' . /** @scrutinizer ignore-call */ __('Documentation', 'pagantis') . '</a>';
Loading history...
607
            $links[] = '<a href="' . PAGANTIS_DOC_URL . '" target="_blank">' . __('API documentation', 'pagantis') . '</a>';
608
            $links[] = '<a href="' . PAGANTIS_SUPPORT_EMAIL . '">' . __('Support', 'pagantis') . '</a>';
609
610
            return $links;
611
        }
612
613
        return $links;
614
    }
615
616
    /**
617
     * Read logs
618
     *
619
     * @param       $data
620
     *
621
     * @global wpdb $wpdb WordPress database abstraction object.
622
     */
623
    public function get_pagantis_logs($data)
624
    {
625
        global $wpdb;
626
        $filters    = ($data->get_params());
627
        $response   = array();
628
        $secretKey  = $filters['secret'];
629
        $from       = $filters['from'];
630
        $to         = $filters['to'];
631
        $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

631
        $cfg        = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
632
        $privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
633
        $tableName  = $wpdb->prefix . PAGANTIS_LOGS_TABLE;
634
        $query      = "SELECT * FROM $tableName WHERE createdAt>$from AND createdAt<$to ORDER BY createdAt DESC";
635
        $results    = $wpdb->get_results($query);
636
        if (isset($results) && $privateKey === $secretKey) {
637
            foreach ($results as $key => $result) {
638
                $response[$key]['timestamp'] = $result->createdAt;
639
                $response[$key]['log']       = json_decode($result->log);
640
            }
641
        } else {
642
            $response['result'] = 'Error';
643
        }
644
        $response = json_encode($response);
645
        header('HTTP/1.1 200', true, 200);
646
        header('Content-Type: application/json', true);
647
        header('Content-Length: ' . strlen($response));
648
        echo($response);
649
        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...
650
    }
651
652
    /**
653
     * Update extra config
654
     *
655
     * @param $data
656
     */
657
    public function updateExtraConfig($data)
658
    {
659
        global $wpdb;
660
        $tableName = $wpdb->prefix . PAGANTIS_CONFIG_TABLE;
661
        $response  = array('status' => null);
662
663
        $filters    = ($data->get_params());
664
        $secretKey  = $filters['secret'];
665
        $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

665
        $cfg        = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
666
        $privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
667
        if ($privateKey !== $secretKey) {
668
            $response['status'] = 401;
669
            $response['result'] = 'Unauthorized';
670
        } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
671
            if (count($_POST)) {
672
                foreach ($_POST as $config => $value) {
673
                    if (isset($this->initialConfig[$config]) && $response['status'] === null) {
674
                        $wpdb->update(
675
                            $tableName,
676
                            array('value' => stripslashes($value)),
677
                            array('config' => $config),
678
                            array('%s'),
679
                            array('%s')
680
                        );
681
                    } else {
682
                        $response['status'] = 400;
683
                        $response['result'] = 'Bad request';
684
                    }
685
                }
686
            } else {
687
                $response['status'] = 422;
688
                $response['result'] = 'Empty data';
689
            }
690
        }
691
692
        if ($response['status'] === null) {
693
            $tableName = $wpdb->prefix . PAGANTIS_CONFIG_TABLE;
694
            $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...
695
            foreach ($dbResult as $value) {
696
                $formattedResult[$value['config']] = $value['value'];
697
            }
698
            $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 695. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
699
        }
700
701
        $result = json_encode($response['result']);
702
        header('HTTP/1.1 ' . $response['status'], true, $response['status']);
703
        header('Content-Type: application/json', true);
704
        header('Content-Length: ' . strlen($result));
705
        echo($result);
706
        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...
707
    }
708
709
    /**
710
     * Read logs
711
     *
712
     * @param $data
713
     */
714
    public function readApi($data)
715
    {
716
        global $wpdb;
717
        $filters        = ($data->get_params());
718
        $response       = array('timestamp' => time());
719
        $secretKey      = $filters['secret'];
720
        $from           = ($filters['from']) ? date_create($filters['from']) : date('Y-m-d', strtotime('-7 day'));
721
        $to             = ($filters['to']) ? date_create($filters['to']) : date('Y-m-d', strtotime('+1 day'));
722
        $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...
723
        $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

723
        $cfg            = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
724
        $privateKey     = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
725
        $tableName      = $wpdb->prefix . PAGANTIS_WC_ORDERS_TABLE;
726
        $tableNameInner = $wpdb->prefix . 'postmeta';
727
        $query          = "SELECT * FROM $tableName tn INNER JOIN $tableNameInner tn2 ON tn2.post_id = tn.id
728
                  WHERE tn.post_type='shop_order' AND tn.post_date>'" . $from->format('Y-m-d') . "' 
729
                  AND tn.post_date<'" . $to->format('Y-m-d') . "' ORDER BY tn.post_date DESC";
730
        $results        = $wpdb->get_results($query);
731
732
        if (isset($results) && $privateKey === $secretKey) {
733
            foreach ($results as $result) {
734
                $key                                          = $result->ID;
735
                $response['message'][$key]['timestamp']       = $result->post_date;
736
                $response['message'][$key]['order_id']        = $key;
737
                $response['message'][$key][$result->meta_key] = $result->meta_value;
738
            }
739
        } else {
740
            $response['result'] = 'Error';
741
        }
742
        $response = json_encode($response);
743
        header('HTTP/1.1 200', true, 200);
744
        header('Content-Type: application/json', true);
745
        header('Content-Length: ' . strlen($response));
746
        echo($response);
747
        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...
748
    }
749
750
    /**
751
     * ENDPOINT - Read logs -> Hook: rest_api_init
752
     *
753
     * @hook rest_api_init
754
     * @return mixed
755
     */
756
    public function register_pg_rest_routes()
757
    {
758
        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

758
        /** @scrutinizer ignore-call */ 
759
        register_rest_route('pagantis/v1', '/logs/(?P<secret>\w+)/(?P<from>\d+)/(?P<to>\d+)', array(
Loading history...
759
            'methods'  => 'GET',
760
            'callback' => array(
761
                $this,
762
                'get_pagantis_logs',
763
            ),
764
        ), true);
765
766
        register_rest_route('pagantis/v1', '/configController/(?P<secret>\w+)', array(
767
            'methods'  => 'GET, POST',
768
            'callback' => array(
769
                $this,
770
                'updateExtraConfig',
771
            ),
772
        ), true);
773
774
        register_rest_route('pagantis/v1', '/api/(?P<secret>\w+)/(?P<from>\w+)/(?P<to>\w+)', array(
775
            'methods'  => 'GET',
776
            'callback' => array(
777
                $this,
778
                'readApi',
779
            ),
780
        ), true);
781
    }
782
783
    /**
784
     * @param $css_quantity_selector
785
     *
786
     * @return mixed|string
787
     */
788
    private function prepareQuantitySelector($css_quantity_selector)
789
    {
790
        if ($css_quantity_selector === 'default' || $css_quantity_selector === '') {
791
            $css_quantity_selector = $this->initialConfig['PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'];
792
        } elseif (! unserialize($css_quantity_selector)) { //in the case of a custom string selector, we keep it
793
            $css_quantity_selector = serialize(array($css_quantity_selector));
794
        }
795
796
        return $css_quantity_selector;
797
    }
798
799
    /**
800
     * @param $css_price_selector
801
     *
802
     * @return mixed|string
803
     */
804
    private function preparePriceSelector($css_price_selector)
805
    {
806
        if ($css_price_selector === 'default' || $css_price_selector === '') {
807
            $css_price_selector = $this->initialConfig['PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'];
808
        } elseif (! unserialize($css_price_selector)) { //in the case of a custom string selector, we keep it
809
            $css_price_selector = serialize(array($css_price_selector));
810
        }
811
812
        return $css_price_selector;
813
    }
814
}
815
816
/**
817
 * Add widget Js
818
 **/
819
function add_pagantis_widget_js()
820
{
821
    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

821
    /** @scrutinizer ignore-call */ 
822
    wp_enqueue_script('pgSDK', 'https://cdn.pagantis.com/js/pg-v2/sdk.js', '', '', true);
Loading history...
822
}
823
824
WC_Pagantis_Plugin::get_instance();
825
826
/**
827
 * Main instance WC_Pagantis_Plugin.
828
 *
829
 * Returns the main instance of WC_Pagantis_Plugin.
830
 *
831
 * @return WC_Pagantis_Plugin
832
 */
833
function PG_WC() // phpcs:ignore
834
{
835
    return WC_Pagantis_Plugin::get_instance();
836
}
837