WcPagantis   F
last analyzed

Complexity

Total Complexity 132

Size/Duplication

Total Lines 826
Duplicated Lines 0 %

Importance

Changes 42
Bugs 0 Features 2
Metric Value
eloc 442
c 42
b 0
f 2
dl 0
loc 826
rs 2
wmc 132

25 Methods

Rating   Name   Duplication   Size   Complexity  
A pagantisPromotedVarSave() 0 8 2
A pagantisPromotedProductTpl() 0 11 1
A pagantisPromotedBulkTemplate() 0 3 1
A loadPagantisTranslation() 0 6 2
A pagantisPromotedBulkTemplateSave() 0 11 2
A __construct() 0 28 1
A pagantisActionLinks() 0 9 1
A pagantisFilterGateways() 0 13 3
A pagantisRowMeta() 0 12 2
A addPagantisGateway() 0 15 2
A prepareQuantitySelector() 0 9 4
A preparePriceSelector() 0 9 4
C pagantisInitProductSimulator() 0 56 14
C updateExtraConfig() 0 51 12
A pagantisAddProductSnippetForVariations() 0 16 6
A pagantisRegisterEndpoint() 0 39 1
B readApi() 0 35 10
C pagantisAddSimulatorHtmlDiv() 0 33 16
A enqueueSimulatorCss() 0 4 1
A checkWcDecimalSeparatorSettings() 0 8 3
A isPromoted() 0 5 3
A checkWcThousandsSeparatorSettings() 0 7 3
B readLogs() 0 28 7
F pagantisActivation() 0 189 29
A checkWcPriceSettings() 0 5 2

How to fix   Complexity   

Complex Class

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

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

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

1
<?php
2
/**
3
 * Plugin Name: Pagantis
4
 * Plugin URI: http://www.pagantis.com/
5
 * Description: Financiar con Pagantis
6
 * Version: 8.6.14
7
 * Author: Pagantis
8
 *
9
 * Text Domain: pagantis
10
 * Domain Path: /languages/
11
 *
12
 */
13
14
//namespace Gateways;
15
16
17
if (!defined('ABSPATH')) {
18
    exit;
19
}
20
21
22
require_once(__DIR__ . '/includes/pg-functions.php');
23
24
/**
25
 * Required minimums and constants
26
 */
27
define('PG_WC_MAIN_FILE', __FILE__);
28
define('PG_ABSPATH', trailingslashit(dirname(PG_WC_MAIN_FILE)));
0 ignored issues
show
Bug introduced by
The function trailingslashit 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

28
define('PG_ABSPATH', /** @scrutinizer ignore-call */ trailingslashit(dirname(PG_WC_MAIN_FILE)));
Loading history...
29
define('PG_VERSION', getModuleVersion());
30
define('PG_ROOT', dirname(__DIR__));
31
define('PG_CONFIG_TABLE_NAME', 'pagantis_config');
32
define('PG_LOGS_TABLE_NAME', 'pagantis_logs');
33
define('PG_CONCURRENCY_TABLE_NAME', 'pagantis_concurrency');
34
define('PG_CART_PROCESS_TABLE', 'cart_process');
35
define('PG_ORDERS_TABLE', 'posts');
36
37
38
class WcPagantis
39
{
40
    const GIT_HUB_URL = 'https://github.com/pagantis/woocommerce';
41
    const PAGANTIS_DOC_URL = 'https://developer.pagantis.com';
42
    const SUPPORT_EML = 'mailto:[email protected]?Subject=woocommerce_plugin';
43
44
45
    public $defaultConfigs = array(
46
        'PAGANTIS_TITLE'=>'Instant financing',
47
        'PAGANTIS_SIMULATOR_DISPLAY_TYPE'=>'sdk.simulator.types.PRODUCT_PAGE',
48
        'PAGANTIS_SIMULATOR_DISPLAY_TYPE_CHECKOUT'=>'sdk.simulator.types.CHECKOUT_PAGE',
49
        'PAGANTIS_SIMULATOR_DISPLAY_SKIN'=>'sdk.simulator.skins.BLUE',
50
        'PAGANTIS_SIMULATOR_DISPLAY_POSITION'=>'hookDisplayProductButtons',
51
        'PAGANTIS_SIMULATOR_START_INSTALLMENTS'=>3,
52
        'PAGANTIS_SIMULATOR_MAX_INSTALLMENTS'=>12,
53
        'PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'=>'default',
54
        'PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION'=>'sdk.simulator.positions.INNER',
55
        'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'=>'a:4:{i:0;s:52:"div.summary *:not(del)>.woocommerce-Price-amount bdi";i:1;s:48:"div.summary *:not(del)>.woocommerce-Price-amount";i:2;s:54:"div.entry-summary *:not(del)>.woocommerce-Price-amount";i:3;s:36:"*:not(del)>.woocommerce-Price-amount";}',
56
        'PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'=>'a:2:{i:0;s:22:"div.quantity input.qty";i:1;s:18:"div.quantity>input";}',
57
        'PAGANTIS_FORM_DISPLAY_TYPE'=>0,
58
        'PAGANTIS_DISPLAY_MIN_AMOUNT'=>1,
59
        'PAGANTIS_DISPLAY_MAX_AMOUNT'=>1500,
60
        'PAGANTIS_URL_OK'=>'',
61
        'PAGANTIS_URL_KO'=>'',
62
        'PAGANTIS_ALLOWED_COUNTRIES' => 'a:3:{i:0;s:2:"es";i:1;s:2:"it";i:2;s:2:"fr";}',
63
        'PAGANTIS_PROMOTION_EXTRA' => '<p>Finance this product <span class="pg-no-interest">without interest!</span></p>',
64
        'PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR' => '.',
65
        'PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR' => ',',
66
        'PAGANTIS_SIMULATOR_DISPLAY_SITUATION' => 'default',
67
        'PAGANTIS_SIMULATOR_SELECTOR_VARIATION' => 'default',
68
        //4x
69
        'PAGANTIS_DISPLAY_MIN_AMOUNT_4x'=>0,
70
        'PAGANTIS_DISPLAY_MAX_AMOUNT_4x'=>800,
71
        'PAGANTIS_TITLE_4x'=>'Hasta 4 pagos, sin coste',
72
73
    );
74
75
    /** @var array $extraConfig */
76
    public $extraConfig;
77
78
    /**
79
     * WC_Pagantis constructor.
80
     */
81
    public function __construct()
82
    {
83
        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

83
        require_once(/** @scrutinizer ignore-call */ plugin_dir_path(__FILE__).'/vendor/autoload.php');
Loading history...
84
        require_once(PG_ABSPATH . '/includes/pg-functions.php');
85
        $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...
86
87
        $this->pagantisActivation();
88
89
        $this->extraConfig = getExtraConfig();
90
91
        load_plugin_textdomain('pagantis', false, dirname(plugin_basename(__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

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

91
        load_plugin_textdomain('pagantis', false, dirname(/** @scrutinizer ignore-call */ plugin_basename(__FILE__)).'/languages');
Loading history...
92
93
        add_filter('woocommerce_payment_gateways', array($this, 'addPagantisGateway'));
0 ignored issues
show
Bug introduced by
The function add_filter was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

93
        /** @scrutinizer ignore-call */ 
94
        add_filter('woocommerce_payment_gateways', array($this, 'addPagantisGateway'));
Loading history...
94
        add_filter('woocommerce_available_payment_gateways', array($this, 'pagantisFilterGateways'), 9999);
95
        add_filter('plugin_row_meta', array($this, 'pagantisRowMeta'), 10, 2);
96
        add_filter('plugin_action_links_'.plugin_basename(__FILE__), array($this, 'pagantisActionLinks'));
97
        add_action('init', array($this, 'checkWcPriceSettings'), 10);
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

97
        /** @scrutinizer ignore-call */ 
98
        add_action('init', array($this, 'checkWcPriceSettings'), 10);
Loading history...
98
        add_action('woocommerce_after_template_part', array($this, 'pagantisAddSimulatorHtmlDiv'), 10);
99
        add_action('woocommerce_single_product_summary', array($this, 'pagantisInitProductSimulator'), 20);
100
        add_action('woocommerce_single_variation', array($this,'pagantisAddProductSnippetForVariations'), 30);
101
        add_action('wp_enqueue_scripts', 'add_pagantis_widget_js');
102
        add_action('rest_api_init', array($this, 'pagantisRegisterEndpoint')); //Endpoint
103
        add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
104
        register_activation_hook(__FILE__, array($this, 'pagantisActivation'));
0 ignored issues
show
Bug introduced by
The function register_activation_hook was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

104
        /** @scrutinizer ignore-call */ 
105
        register_activation_hook(__FILE__, array($this, 'pagantisActivation'));
Loading history...
105
        add_action('woocommerce_product_options_general_product_data', array($this, 'pagantisPromotedProductTpl'));
106
        add_action('woocommerce_process_product_meta', array($this, 'pagantisPromotedVarSave'));
107
        add_action('woocommerce_product_bulk_edit_start', array($this,'pagantisPromotedBulkTemplate'));
108
        add_action('woocommerce_product_bulk_edit_save', array($this,'pagantisPromotedBulkTemplateSave'));
109
    }
110
111
    /**
112
     * Piece of html code to insert into BULK admin edit
113
     */
114
    public function pagantisPromotedBulkTemplate()
115
    {
116
        echo '<div class="inline-edit-group">
117
			<label class="alignleft">
118
				<span class="title">Pagantis promoted</span>
119
				<span class="input-text-wrap">
120
                    <input type="checkbox" id="pagantis_promoted" name="pagantis_promoted"/>
121
				</span>
122
			</label>
123
		</div>';
124
    }
125
126
    /**
127
     * Php code to save our meta after a bulk admin edit
128
     * @param $product
129
     */
130
    public function pagantisPromotedBulkTemplateSave($product)
131
    {
132
        $post_id = $product->get_id();
133
        $pagantis_promoted_value = $_REQUEST['pagantis_promoted'];
134
        if ($pagantis_promoted_value === 'on') {
135
            $pagantis_promoted_value = 'yes';
136
        } else {
137
            $pagantis_promoted_value = 'no';
138
        }
139
140
        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

140
        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

140
        /** @scrutinizer ignore-call */ 
141
        update_post_meta($post_id, 'custom_product_pagantis_promoted', esc_attr($pagantis_promoted_value));
Loading history...
141
    }
142
143
    /**
144
     * Piece of html code to insert into PRODUCT admin edit
145
     */
146
    public function pagantisPromotedProductTpl()
147
    {
148
        global $post;
149
        $_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

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

150
        /** @scrutinizer ignore-call */ 
151
        woocommerce_wp_checkbox(
Loading history...
151
            array(
152
                'id' => 'pagantis_promoted',
153
                'label' => __('Pagantis promoted', 'woocommerce'),
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

153
                'label' => /** @scrutinizer ignore-call */ __('Pagantis promoted', 'woocommerce'),
Loading history...
154
                'value' => $_product['custom_product_pagantis_promoted']['0'],
155
                'cbvalue' => 'yes',
156
                'echo' => true
157
            )
158
        );
159
    }
160
161
    /**
162
     *  Php code to save our meta after a PRODUCT admin edit
163
     * @param $post_id
164
     */
165
    public function pagantisPromotedVarSave($post_id)
166
    {
167
        $pagantis_promoted_value = $_POST['pagantis_promoted'];
168
        if ($pagantis_promoted_value !== 'yes') {
169
            $pagantis_promoted_value = 'no';
170
        }
171
172
        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

172
        /** @scrutinizer ignore-call */ 
173
        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

172
        update_post_meta($post_id, 'custom_product_pagantis_promoted', /** @scrutinizer ignore-call */ esc_attr($pagantis_promoted_value));
Loading history...
173
    }
174
175
    /*
176
     * Replace 'textdomain' with your plugin's textdomain. e.g. 'woocommerce'.
177
     * File to be named, for example, yourtranslationfile-en_GB.mo
178
     * File to be placed, for example, wp-content/languages/textdomain/yourtranslationfile-en_GB.mo
179
     */
180
    public function loadPagantisTranslation($mofile, $domain)
181
    {
182
        if ('pagantis' === $domain) {
183
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . get_locale() . '.mo';
0 ignored issues
show
Bug introduced by
The function get_locale was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

183
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . /** @scrutinizer ignore-call */ get_locale() . '.mo';
Loading history...
Bug introduced by
The constant WP_LANG_DIR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
184
        }
185
        return $mofile;
186
    }
187
188
    /**
189
     * Sql table
190
     */
191
    public function pagantisActivation()
192
    {
193
        global $wpdb;
194
195
        $tableName = $wpdb->prefix.PG_CONCURRENCY_TABLE_NAME;
196
        if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName) {
197
            $charset_collate = $wpdb->get_charset_collate();
198
            $sql = "CREATE TABLE $tableName ( order_id int NOT NULL,  
199
                    createdAt timestamp DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY id (order_id)) $charset_collate";
200
            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...
201
            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

201
            /** @scrutinizer ignore-call */ 
202
            dbDelta($sql);
Loading history...
202
        }
203
204
        $tableName = $wpdb->prefix.PG_CONFIG_TABLE_NAME;
205
206
        //Check if table exists
207
        $tableExists = $wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName;
208
        if ($tableExists) {
209
            $charset_collate = $wpdb->get_charset_collate();
210
            $sql = "CREATE TABLE IF NOT EXISTS $tableName (
211
                                id int NOT NULL AUTO_INCREMENT, 
212
                                config varchar(60) NOT NULL, 
213
                                value varchar(1000) NOT NULL, 
214
                                UNIQUE KEY id(id)) $charset_collate";
215
216
            require_once(ABSPATH.'wp-admin/includes/upgrade.php');
217
            dbDelta($sql);
218
        } else {
219
            //Updated value field to adapt to new length < v8.0.1
220
            $query = "select COLUMN_TYPE FROM information_schema.COLUMNS where TABLE_NAME='$tableName' AND COLUMN_NAME='value'";
221
            $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...
222
            if ($results['0']['COLUMN_TYPE'] == 'varchar(100)') {
223
                $sql = "ALTER TABLE $tableName MODIFY value varchar(1000)";
224
                $wpdb->query($sql);
225
            }
226
227
            //Adapting selector to array < v8.1.1
228
            $query = "select * from $tableName where config='PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR' 
229
                               or config='PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'";
230
            $dbCurrentConfig = $wpdb->get_results($query, ARRAY_A);
231
            foreach ($dbCurrentConfig as $item) {
232
                if ($item['config'] == 'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR') {
233
                    $css_price_selector = $this->preparePriceSelector($item['value']);
234
                    if ($item['value'] != $css_price_selector) {
235
                        $wpdb->update(
236
                            $tableName,
237
                            array('value' => stripslashes($css_price_selector)),
238
                            array('config' => 'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'),
239
                            array('%s'),
240
                            array('%s')
241
                        );
242
                    }
243
                } elseif ($item['config'] == 'PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR') {
244
                    $css_quantity_selector = $this->prepareQuantitySelector($item['value']);
245
                    if ($item['value'] != $css_quantity_selector) {
246
                        $wpdb->update(
247
                            $tableName,
248
                            array('value' => stripslashes($css_quantity_selector)),
249
                            array('config' => 'PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'),
250
                            array('%s'),
251
                            array('%s')
252
                        );
253
                    }
254
                }
255
            }
256
        }
257
258
        // Making sure DB tables are created < v8.6.9
259
        if (!isPgTableCreated(PG_LOGS_TABLE_NAME)){
260
            createLogsTable();
261
        }
262
        if (isPgTableCreated(PG_CART_PROCESS_TABLE)){
263
            alterCartProcessTable();
264
        }
265
266
        if (!isPgTableCreated(PG_CART_PROCESS_TABLE)) {
267
            checkCartProcessTable();
268
        }
269
270
        //Adapting selector to array < v8.2.2
271
        $tableName = $wpdb->prefix.PG_CONFIG_TABLE_NAME;
272
        $query = "select * from $tableName where config='PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'";
273
        $results = $wpdb->get_results($query, ARRAY_A);
274
        if (count($results) == 0) {
275
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR', 'value'  => '.'), array('%s', '%s'));
276
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR', 'value'  => ','), array('%s', '%s'));
277
        }
278
279
        //Adding new selector < v8.3.0
280
        $tableName = $wpdb->prefix.PG_CONFIG_TABLE_NAME;
281
        $query = "select * from $tableName where config='PAGANTIS_DISPLAY_MAX_AMOUNT'";
282
        $results = $wpdb->get_results($query, ARRAY_A);
283
        if (count($results) == 0) {
284
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_DISPLAY_MAX_AMOUNT', 'value'  => '0'), array('%s', '%s'));
285
        }
286
287
        //Adding new selector < v8.3.2
288
        $tableName = $wpdb->prefix.PG_CONFIG_TABLE_NAME;
289
        $query = "select * from $tableName where config='PAGANTIS_SIMULATOR_DISPLAY_SITUATION'";
290
        $results = $wpdb->get_results($query, ARRAY_A);
291
        if (count($results) == 0) {
292
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_SIMULATOR_DISPLAY_SITUATION', 'value'  => 'default'), array('%s', '%s'));
293
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_SIMULATOR_SELECTOR_VARIATION', 'value'  => 'default'), array('%s', '%s'));
294
        }
295
296
297
        //Adding new selector < v8.3.3
298
        $tableName = $wpdb->prefix.PG_CONFIG_TABLE_NAME;
299
        $query = "select * from $tableName where config='PAGANTIS_SIMULATOR_DISPLAY_TYPE_CHECKOUT'";
300
        $results = $wpdb->get_results($query, ARRAY_A);
301
        if (count($results) == 0) {
302
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_SIMULATOR_DISPLAY_TYPE_CHECKOUT', 'value'  => 'sdk.simulator.types.CHECKOUT_PAGE'), array('%s', '%s'));
303
            $wpdb->update($tableName, array('value' => 'sdk.simulator.types.PRODUCT_PAGE'), array('config' => 'PAGANTIS_SIMULATOR_DISPLAY_TYPE'), array('%s'), array('%s'));
304
        }
305
306
        //Adapting to variable selector < v8.3.6
307
        $variableSelector="div.summary div.woocommerce-variation.single_variation > div.woocommerce-variation-price span.price";
308
        $tableName = $wpdb->prefix.PG_CONFIG_TABLE_NAME;
309
        $query = "select * from $tableName where config='PAGANTIS_SIMULATOR_SELECTOR_VARIATION' and value='default'";
310
        $results = $wpdb->get_results($query, ARRAY_A);
311
        if (count($results) == 0) {
312
            $wpdb->update($tableName, array('value' => $variableSelector), array('config' => 'PAGANTIS_SIMULATOR_SELECTOR_VARIATION'), array('%s'), array('%s'));
313
        }
314
315
        //Adapting vars to 4x < v8.6.x
316
        $tableName = $wpdb->prefix.PG_CONFIG_TABLE_NAME;
317
        $query = "select * from $tableName where config='PAGANTIS_TITLE_4x'";
318
        $results = $wpdb->get_results($query, ARRAY_A);
319
        if (count($results) == 0) {
320
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_TITLE_4x', 'value'  => 'Until 4 installments, without fees'), array('%s', '%s'));
321
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_DISPLAY_MIN_AMOUNT_4x', 'value'  => 1), array('%s', '%s'));
322
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_DISPLAY_MAX_AMOUNT_4x', 'value'  => 800), array('%s', '%s'));
323
324
            $wpdb->update($tableName, array('value' => 'Instant financing'), array('config' => 'PAGANTIS_TITLE'), array('%s'), array('%s'));
325
            $wpdb->update($tableName, array('value' => 1500), array('config' => 'PAGANTIS_DISPLAY_MAX_AMOUNT'), array('%s'), array('%s'));
326
        }
327
328
        //Adapting situation var of 4x < v8.6.2
329
        $tableName = $wpdb->prefix.PG_CONFIG_TABLE_NAME;
330
        $query = "select * from $tableName where config='PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR_4X'";
331
        $results = $wpdb->get_results($query, ARRAY_A);
332
        if (count($results) == 0) {
333
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR_4X', 'value'  => 'default'), array('%s', '%s'));
334
        }
335
336
        //Adding WC price separator verifications to adapt extra config dynamically < v8.3.9
337
        if (!areDecimalSeparatorEqual()) {
338
            updateDecimalSeparatorDbConfig();
339
        }
340
        if (!areThousandsSeparatorEqual()) {
341
            updateThousandsSeparatorDbConfig();
342
        }
343
344
        //Adapting product price selector < v8.6.7
345
        $tableName = $wpdb->prefix.PG_CONFIG_TABLE_NAME;
346
        $query = "select * from $tableName where config='PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'";
347
        $results = $wpdb->get_results($query, ARRAY_A);
348
        if (count($results) == 0) {
349
            $wpdb->update($tableName, array('value' => 'a:4:{i:0;s:52:"div.summary *:not(del)>.woocommerce-Price-amount bdi";i:1;s:48:"div.summary *:not(del)>.woocommerce-Price-amount";i:2;s:54:"div.entry-summary *:not(del)>.woocommerce-Price-amount";i:3;s:36:"*:not(del)>.woocommerce-Price-amount";}'), array('config' => 'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'), 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($this->defaultConfigs, $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
     * Checks the WC settings to know if we should modify our config
384
     */
385
    public function checkWcPriceSettings()
386
    {
387
        if (class_exists( 'WooCommerce' ) ){
388
            $this->checkWcDecimalSeparatorSettings();
389
            $this->checkWcThousandsSeparatorSettings();
390
        }
391
    }
392
393
    /**
394
     * Check woocommerce_price_thousand_sep and update our config if necessary
395
     */
396
    private function checkWcThousandsSeparatorSettings()
397
    {
398
        if (areThousandsSeparatorEqual()) {
399
            return;
400
        }
401
        if (!areThousandsSeparatorEqual()) {
402
            updateThousandsSeparatorDbConfig();
403
        }
404
    }
405
406
    /**
407
     * Check woocommerce_price_decimal_sep and update our config if necessary
408
     */
409
    private function checkWcDecimalSeparatorSettings()
410
    {
411
        if (areDecimalSeparatorEqual()) {
412
            return;
413
        }
414
415
        if (!areDecimalSeparatorEqual()) {
416
            updateDecimalSeparatorDbConfig();
417
        }
418
    }
419
420
    /**
421
     *  Pushes the simulator div depending on the config and plugin settings
422
     *
423
     * @param $template_name
424
     *
425
     * @return bool|mixed|void
426
     * @hooked woocommerce_after_template_part - 10
427
     * @see wc_get_template
428
     */
429
    public function pagantisAddSimulatorHtmlDiv($template_name)
430
    {
431
        $areSimulatorTypesValid = isSimulatorTypeValid(
432
            getConfigValue('PAGANTIS_SIMULATOR_DISPLAY_TYPE'),
433
            array('sdk.simulator.types.SELECTABLE_TEXT_CUSTOM',
434
                'sdk.simulator.types.PRODUCT_PAGE')
435
        );
436
        $isPriceTplPresent = isTemplatePresent($template_name, array('single-product/price.php'));
437
        $isAtcTplPresent = isTemplatePresent(
438
            $template_name,
439
            array('single-product/add-to-cart/variation-add-to-cart-button.php',
440
                'single-product/add-to-cart/variation.php','single-product/add-to-cart/simple.php')
441
        );
442
443
        $html = apply_filters('pagantis_simulator_selector_html', '<div class="mainPagantisSimulator"></div><div class="pagantisSimulator"></div>');
0 ignored issues
show
Bug introduced by
The function apply_filters 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

443
        $html = /** @scrutinizer ignore-call */ apply_filters('pagantis_simulator_selector_html', '<div class="mainPagantisSimulator"></div><div class="pagantisSimulator"></div>');
Loading history...
444
445
446
        $pagantisSimulator = 'enabled';
447
        if (!isPluginEnabled() || !areMerchantKeysSet() || !isSimulatorEnabled() || !isCountryShopContextValid() || !isProductAmountValid()) {
448
            $pagantisSimulator = 'disabled';
449
        }
450
451
        $pagantisSimulator4x = 'enabled';
452
        if (!isPluginEnabled4x() || !areMerchantKeysSet4x()  || !isCountryShopContextValid() || !isProductAmountValid4x()) {
453
            $pagantisSimulator4x = 'disabled';
454
        }
455
        if ($pagantisSimulator === 'disabled' && $pagantisSimulator4x === 'disabled') {
456
            return;
457
        }
458
459
        if (($areSimulatorTypesValid && $isPriceTplPresent) || (!$areSimulatorTypesValid && $isAtcTplPresent)) {
460
            self::enqueueSimulatorCss();
461
            echo $html;
462
        }
463
    }
464
465
466
    /**
467
     * Init code required to update price for products with variations
468
     *
469
     */
470
    public function pagantisAddProductSnippetForVariations()
471
    {
472
        global $product;
473
        if (!isPluginEnabled() || !areMerchantKeysSet() || !isSimulatorEnabled() || !isCountryShopContextValid() || !isProductAmountValid()) {
474
            return;
475
        }
476
477
        wp_register_script('pg-product-variation-simulator', plugins_url('assets/js/pg-product-variation-simulator.js', PG_WC_MAIN_FILE), array('pg-product-simulator'), '', true);
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

477
        /** @scrutinizer ignore-call */ 
478
        wp_register_script('pg-product-variation-simulator', plugins_url('assets/js/pg-product-variation-simulator.js', PG_WC_MAIN_FILE), array('pg-product-simulator'), '', true);
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

477
        wp_register_script('pg-product-variation-simulator', /** @scrutinizer ignore-call */ plugins_url('assets/js/pg-product-variation-simulator.js', PG_WC_MAIN_FILE), array('pg-product-simulator'), '', true);
Loading history...
478
479
        $variationSimulatorData = array(
480
            'variationSelector' =>  $this->extraConfig['PAGANTIS_SIMULATOR_SELECTOR_VARIATION'],
481
            'productType' => $product->get_type()
482
        );
483
484
        wp_localize_script('pg-product-variation-simulator', 'variationSimulatorData', $variationSimulatorData);
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

484
        /** @scrutinizer ignore-call */ 
485
        wp_localize_script('pg-product-variation-simulator', 'variationSimulatorData', $variationSimulatorData);
Loading history...
485
        wp_enqueue_script('pg-product-variation-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

485
        /** @scrutinizer ignore-call */ 
486
        wp_enqueue_script('pg-product-variation-simulator');
Loading history...
486
    }
487
488
    /**
489
     * @return string|void
490
     *
491
     */
492
    public function pagantisInitProductSimulator()
493
    {
494
        global $product;
495
496
        //12x
497
        $pagantisSimulator = 'enabled';
498
499
        wp_register_script('pg-product-simulator', plugins_url('assets/js/pg-product-simulator.js', PG_WC_MAIN_FILE), array(), '', true);
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

499
        wp_register_script('pg-product-simulator', /** @scrutinizer ignore-call */ plugins_url('assets/js/pg-product-simulator.js', PG_WC_MAIN_FILE), array(), '', true);
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

499
        /** @scrutinizer ignore-call */ 
500
        wp_register_script('pg-product-simulator', plugins_url('assets/js/pg-product-simulator.js', PG_WC_MAIN_FILE), array(), '', true);
Loading history...
500
        $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

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

501
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
502
        if (!isPluginEnabled() || !areMerchantKeysSet() || !isSimulatorEnabled() || !isCountryShopContextValid() || !isProductAmountValid()) {
503
            $pagantisSimulator = 'disabled';
504
        }
505
506
        $pagantisSimulator4x = 'enabled';
507
        if (!isPluginEnabled4x() || !areMerchantKeysSet4x() || !isCountryShopContextValid() || !isProductAmountValid4x()) {
508
            $pagantisSimulator4x = 'disabled';
509
        }
510
511
        if ($pagantisSimulator === 'disabled' && $pagantisSimulator4x === 'disabled') {
512
            return;
513
        }
514
515
        $totalPrice = $product->get_price();
516
        $formattedInstallments = number_format($totalPrice/4, 2);
517
        $simulatorMessage = sprintf(__('or 4 installments of %s€, without fees, with ', 'pagantis'), $formattedInstallments);
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

517
        $simulatorMessage = sprintf(/** @scrutinizer ignore-call */ __('or 4 installments of %s€, without fees, with ', 'pagantis'), $formattedInstallments);
Loading history...
518
        $post_id = $product->get_id();
519
        $logo = 'https://cdn.digitalorigin.com/assets/master/logos/pg-130x30.svg';
520
        $simulatorData = array(
521
            'total'    => is_numeric($product->get_price()) ? $product->get_price() : 0,
522
            'public_key' => $settings['pagantis_public_key'],
523
            'simulator_type' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE'],
524
            'positionSelector' => $this->extraConfig['PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'],
525
            'positionSelector4x' => $this->extraConfig['PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR_4X'],
526
            'quantitySelector' => unserialize($this->extraConfig['PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR']),
527
            'priceSelector' => unserialize($this->extraConfig['PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR']),
528
            'totalAmount' => is_numeric($product->get_price()) ? $product->get_price() : 0,
529
            'locale' => $locale,
530
            'country' => $locale,
531
            'promoted' => $this->isPromoted($post_id),
532
            'promotedMessage' => $this->extraConfig['PAGANTIS_PROMOTION_EXTRA'],
533
            'thousandSeparator' => $this->extraConfig['PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'],
534
            'decimalSeparator' => $this->extraConfig['PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR'],
535
            'pagantisQuotesStart' => $this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS'],
536
            'pagantisSimulatorSkin' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_SKIN'],
537
            'pagantisSimulatorPosition' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION'],
538
            'finalDestination' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_SITUATION'],
539
            'variationSelector' => $this->extraConfig['PAGANTIS_SIMULATOR_SELECTOR_VARIATION'],
540
            'productType' => $product->get_type(),
541
            'pagantisSimulator' => $pagantisSimulator,
542
            'pagantisSimulator4x' => $pagantisSimulator4x,
543
            'simulatorMessage' => "$simulatorMessage<img class='mainImageLogo' src='$logo'/>"
544
        );
545
546
        wp_localize_script('pg-product-simulator', 'simulatorData', $simulatorData);
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

546
        /** @scrutinizer ignore-call */ 
547
        wp_localize_script('pg-product-simulator', 'simulatorData', $simulatorData);
Loading history...
547
        wp_enqueue_script('pg-product-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

547
        /** @scrutinizer ignore-call */ 
548
        wp_enqueue_script('pg-product-simulator');
Loading history...
548
    }
549
550
    /**
551
     * Add Pagantis to payments list.
552
     *
553
     * @param $methods
554
     *
555
     * @return array
556
     */
557
    public function addPagantisGateway($methods)
558
    {
559
        if (! class_exists('WC_Payment_Gateway')) {
560
            return $methods;
561
        }
562
563
        //4x
564
        include_once('controllers/paymentController4x.php');
565
        $methods[] = 'WcPagantis4xGateway';
566
567
        //12x
568
        include_once('controllers/paymentController.php');
569
        $methods[] = 'WcPagantisGateway';
570
571
        return $methods;
572
    }
573
574
    /**
575
     * Initialize WC_Pagantis class
576
     *
577
     * @param $methods
578
     *
579
     * @return mixed
580
     */
581
    public function pagantisFilterGateways($methods)
582
    {
583
        $pagantis4x = new WcPagantis4xGateway();
584
        if (!$pagantis4x->is_available()) {
585
            unset($methods['pagantis4x']);
586
        }
587
588
        $pagantis = new WcPagantisGateway();
589
        if (!$pagantis->is_available()) {
590
            unset($methods['pagantis']);
591
        }
592
593
        return $methods;
594
    }
595
596
    /**
597
     * Add links to Plugin description
598
     *
599
     * @param $links
600
     *
601
     * @return mixed
602
     */
603
    public function pagantisActionLinks($links)
604
    {
605
        $params_array = array('page' => 'wc-settings', 'tab' => 'checkout', 'section' => 'pagantis');
606
        $setting_url  = esc_url(add_query_arg($params_array, admin_url('admin.php?')));
0 ignored issues
show
Bug introduced by
The function add_query_arg was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

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

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

606
        $setting_url  = esc_url(add_query_arg($params_array, /** @scrutinizer ignore-call */ admin_url('admin.php?')));
Loading history...
607
        $setting_link = '<a href="'.$setting_url.'">'.__('Settings', 'pagantis').'</a>';
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

607
        $setting_link = '<a href="'.$setting_url.'">'./** @scrutinizer ignore-call */ __('Settings', 'pagantis').'</a>';
Loading history...
608
609
        array_unshift($links, $setting_link);
610
611
        return $links;
612
    }
613
614
    /**
615
     * Add links to Plugin options
616
     *
617
     * @param $links
618
     * @param $file
619
     *
620
     * @return array
621
     */
622
    public function pagantisRowMeta($links, $file)
623
    {
624
        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

624
        if ($file == /** @scrutinizer ignore-call */ plugin_basename(__FILE__)) {
Loading history...
625
            $links[] = '<a href="'.WcPagantis::GIT_HUB_URL.'" target="_blank">'.__('Documentation', 'pagantis').'</a>';
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

625
            $links[] = '<a href="'.WcPagantis::GIT_HUB_URL.'" target="_blank">'./** @scrutinizer ignore-call */ __('Documentation', 'pagantis').'</a>';
Loading history...
626
            $links[] = '<a href="'.WcPagantis::PAGANTIS_DOC_URL.'" target="_blank">'.
627
                       __('API documentation', 'pagantis').'</a>';
628
            $links[] = '<a href="'.WcPagantis::SUPPORT_EML.'">'.__('Support', 'pagantis').'</a>';
629
630
            return $links;
631
        }
632
633
        return $links;
634
    }
635
636
    /**
637
     * Read logs
638
     */
639
    public function readLogs($data)
640
    {
641
        global $wpdb;
642
        $filters   = ($data->get_params());
643
        $response  = array();
644
        $secretKey = $filters['secret'];
645
        $from = $filters['from'];
646
        $to   = $filters['to'];
647
        $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

647
        $cfg  = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
648
        $privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
649
        $privateKey4x = isset($cfg['pagantis_private_key_4x']) ? $cfg['pagantis_private_key_4x'] : null;
650
        $tableName = $wpdb->prefix.PG_LOGS_TABLE_NAME;
651
        $query = "select * from $tableName where createdAt>$from and createdAt<$to order by createdAt desc";
652
        $results = $wpdb->get_results($query);
653
        if (isset($results) && ($privateKey == $secretKey || $privateKey4x == $secretKey)) {
654
            foreach ($results as $key => $result) {
655
                $response[$key]['timestamp'] = $result->createdAt;
656
                $response[$key]['log']       = json_decode($result->log);
657
            }
658
        } else {
659
            $response['result'] = 'Error';
660
        }
661
        $response = json_encode($response);
662
        header("HTTP/1.1 200", true, 200);
663
        header('Content-Type: application/json', true);
664
        header('Content-Length: '.strlen($response));
665
        echo($response);
666
        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...
667
    }
668
669
    /**
670
     * Update extra config
671
     */
672
    public function updateExtraConfig($data)
673
    {
674
        global $wpdb;
675
        $tableName = $wpdb->prefix.PG_CONFIG_TABLE_NAME;
676
        $response = array('status'=>null);
677
678
        $filters   = ($data->get_params());
679
        $secretKey = $filters['secret'];
680
        $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

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

737
        $cfg  = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
738
        $privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
739
        $privateKey4x = isset($cfg['pagantis_private_key_4x']) ? $cfg['pagantis_private_key_4x'] : null;
740
        $tableName = $wpdb->prefix.PG_ORDERS_TABLE;
741
        $tableNameInner = $wpdb->prefix.'postmeta';
742
        $query = "select * from $tableName tn INNER JOIN $tableNameInner tn2 ON tn2.post_id = tn.id
743
                  where tn.post_type='shop_order' and tn.post_date>'".$from->format("Y-m-d")."' 
744
                  and tn.post_date<'".$to->format("Y-m-d")."' order by tn.post_date desc";
745
        $results = $wpdb->get_results($query);
746
747
        if (isset($results) && ($privateKey == $secretKey || $privateKey4x == $secretKey)) {
748
            foreach ($results as $result) {
749
                $key = $result->ID;
750
                $response['message'][$key]['timestamp'] = $result->post_date;
751
                $response['message'][$key]['order_id'] = $key;
752
                $response['message'][$key][$result->meta_key] = $result->meta_value;
753
            }
754
        } else {
755
            $response['result'] = 'Error';
756
        }
757
        $response = json_encode($response);
758
        header("HTTP/1.1 200", true, 200);
759
        header('Content-Type: application/json', true);
760
        header('Content-Length: '.strlen($response));
761
        echo($response);
762
        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...
763
    }
764
765
    /**
766
     * ENDPOINT - Read logs -> Hook: rest_api_init
767
     * @return mixed
768
     */
769
    public function pagantisRegisterEndpoint()
770
    {
771
        register_rest_route(
0 ignored issues
show
Bug introduced by
The function register_rest_route was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

771
        /** @scrutinizer ignore-call */ 
772
        register_rest_route(
Loading history...
772
            'pagantis/v1',
773
            '/logs/(?P<secret>\w+)/(?P<from>\d+)/(?P<to>\d+)',
774
            array(
775
                'methods'  => 'GET',
776
                'callback' => array(
777
                    $this,
778
                    'readLogs'),
779
                'permission_callback' => '__return_true',
780
            ),
781
            true
782
        );
783
784
        register_rest_route(
785
            'pagantis/v1',
786
            '/configController/(?P<secret>\w+)',
787
            array(
788
                'methods'  => 'GET, POST',
789
                'callback' => array(
790
                    $this,
791
                    'updateExtraConfig'),
792
                'permission_callback' => '__return_true',
793
            ),
794
            true
795
        );
796
797
        register_rest_route(
798
            'pagantis/v1',
799
            '/api/(?P<secret>\w+)/(?P<from>\w+)/(?P<to>\w+)',
800
            array(
801
                'methods'  => 'GET',
802
                'callback' => array(
803
                    $this,
804
                    'readApi'),
805
                'permission_callback' => '__return_true',
806
            ),
807
            true
808
        );
809
    }
810
811
812
813
    /**
814
     * @param $css_quantity_selector
815
     *
816
     * @return mixed|string
817
     */
818
    private function prepareQuantitySelector($css_quantity_selector)
819
    {
820
        if ($css_quantity_selector == 'default' || $css_quantity_selector == '') {
821
            $css_quantity_selector = $this->defaultConfigs['PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'];
822
        } elseif (!unserialize($css_quantity_selector)) { //in the case of a custom string selector, we keep it
823
            $css_quantity_selector = serialize(array($css_quantity_selector));
824
        }
825
826
        return $css_quantity_selector;
827
    }
828
829
    /**
830
     * @param $css_price_selector
831
     *
832
     * @return mixed|string
833
     */
834
    private function preparePriceSelector($css_price_selector)
835
    {
836
        if ($css_price_selector == 'default' || $css_price_selector == '') {
837
            $css_price_selector = $this->defaultConfigs['PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'];
838
        } elseif (!unserialize($css_price_selector)) { //in the case of a custom string selector, we keep it
839
            $css_price_selector = serialize(array($css_price_selector));
840
        }
841
842
        return $css_price_selector;
843
    }
844
845
    /**
846
     * @param $product_id
847
     *
848
     * @return string
849
     */
850
    private function isPromoted($product_id)
851
    {
852
        $metaProduct = get_post_meta($product_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

852
        $metaProduct = /** @scrutinizer ignore-call */ get_post_meta($product_id);
Loading history...
853
        return (array_key_exists('custom_product_pagantis_promoted', $metaProduct) &&
854
                $metaProduct['custom_product_pagantis_promoted']['0'] === 'yes') ? 'true' : 'false';
855
    }
856
857
    /**
858
     * @see wp_enqueue_style
859
     */
860
    private static function enqueueSimulatorCss()
861
    {
862
        wp_enqueue_style('pg_simulator_style', plugins_url('assets/css/pg-simulator-style.css', PG_WC_MAIN_FILE));
0 ignored issues
show
Bug introduced by
The function wp_enqueue_style 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

862
        /** @scrutinizer ignore-call */ 
863
        wp_enqueue_style('pg_simulator_style', plugins_url('assets/css/pg-simulator-style.css', PG_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

862
        wp_enqueue_style('pg_simulator_style', /** @scrutinizer ignore-call */ plugins_url('assets/css/pg-simulator-style.css', PG_WC_MAIN_FILE));
Loading history...
863
        wp_enqueue_style('pg_sim_gfonts', 'https://fonts.googleapis.com/css?family=Open+Sans:400&display=swap');
864
    }
865
}
866
867
/**
868
 * Add widget Js
869
 **/
870
function add_pagantis_widget_js()
871
{
872
    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

872
    /** @scrutinizer ignore-call */ 
873
    wp_enqueue_script('pgSDK', 'https://cdn.pagantis.com/js/pg-v2/sdk.js', '', '', true);
Loading history...
873
}
874
875
$WcPagantis = new WcPagantis();
876