Completed
Push — master ( bcf6c3...37bd96 )
by
unknown
13s queued 10s
created

WcPagantis::enqueueSimulatorCss()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
1
<?php
2
/**
3
 * Plugin Name: Pagantis
4
 * Plugin URI: http://www.pagantis.com/
5
 * Description: Financiar con Pagantis
6
 * Version: 8.6.9
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', getModuleComposerVersion(PG_ABSPATH));
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
        //Adapting selector to array < v8.2.2
259
        $tableName = $wpdb->prefix.PG_CONFIG_TABLE_NAME;
260
        $query = "select * from $tableName where config='PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'";
261
        $results = $wpdb->get_results($query, ARRAY_A);
262
        if (count($results) == 0) {
263
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR', 'value'  => '.'), array('%s', '%s'));
264
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR', 'value'  => ','), array('%s', '%s'));
265
        }
266
267
        //Adding new selector < v8.3.0
268
        $tableName = $wpdb->prefix.PG_CONFIG_TABLE_NAME;
269
        $query = "select * from $tableName where config='PAGANTIS_DISPLAY_MAX_AMOUNT'";
270
        $results = $wpdb->get_results($query, ARRAY_A);
271
        if (count($results) == 0) {
272
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_DISPLAY_MAX_AMOUNT', 'value'  => '0'), array('%s', '%s'));
273
        }
274
275
        //Adding new selector < v8.3.2
276
        $tableName = $wpdb->prefix.PG_CONFIG_TABLE_NAME;
277
        $query = "select * from $tableName where config='PAGANTIS_SIMULATOR_DISPLAY_SITUATION'";
278
        $results = $wpdb->get_results($query, ARRAY_A);
279
        if (count($results) == 0) {
280
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_SIMULATOR_DISPLAY_SITUATION', 'value'  => 'default'), array('%s', '%s'));
281
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_SIMULATOR_SELECTOR_VARIATION', 'value'  => 'default'), array('%s', '%s'));
282
        }
283
284
285
        //Adding new selector < v8.3.3
286
        $tableName = $wpdb->prefix.PG_CONFIG_TABLE_NAME;
287
        $query = "select * from $tableName where config='PAGANTIS_SIMULATOR_DISPLAY_TYPE_CHECKOUT'";
288
        $results = $wpdb->get_results($query, ARRAY_A);
289
        if (count($results) == 0) {
290
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_SIMULATOR_DISPLAY_TYPE_CHECKOUT', 'value'  => 'sdk.simulator.types.CHECKOUT_PAGE'), array('%s', '%s'));
291
            $wpdb->update($tableName, array('value' => 'sdk.simulator.types.PRODUCT_PAGE'), array('config' => 'PAGANTIS_SIMULATOR_DISPLAY_TYPE'), array('%s'), array('%s'));
292
        }
293
294
        //Adapting to variable selector < v8.3.6
295
        $variableSelector="div.summary div.woocommerce-variation.single_variation > div.woocommerce-variation-price span.price";
296
        $tableName = $wpdb->prefix.PG_CONFIG_TABLE_NAME;
297
        $query = "select * from $tableName where config='PAGANTIS_SIMULATOR_SELECTOR_VARIATION' and value='default'";
298
        $results = $wpdb->get_results($query, ARRAY_A);
299
        if (count($results) == 0) {
300
            $wpdb->update($tableName, array('value' => $variableSelector), array('config' => 'PAGANTIS_SIMULATOR_SELECTOR_VARIATION'), array('%s'), array('%s'));
301
        }
302
303
        //Adapting vars to 4x < v8.6.x
304
        $tableName = $wpdb->prefix.PG_CONFIG_TABLE_NAME;
305
        $query = "select * from $tableName where config='PAGANTIS_TITLE_4x'";
306
        $results = $wpdb->get_results($query, ARRAY_A);
307
        if (count($results) == 0) {
308
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_TITLE_4x', 'value'  => 'Until 4 installments, without fees'), array('%s', '%s'));
309
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_DISPLAY_MIN_AMOUNT_4x', 'value'  => 1), array('%s', '%s'));
310
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_DISPLAY_MAX_AMOUNT_4x', 'value'  => 800), array('%s', '%s'));
311
312
            $wpdb->update($tableName, array('value' => 'Instant financing'), array('config' => 'PAGANTIS_TITLE'), array('%s'), array('%s'));
313
            $wpdb->update($tableName, array('value' => 1500), array('config' => 'PAGANTIS_DISPLAY_MAX_AMOUNT'), array('%s'), array('%s'));
314
        }
315
316
        //Adapting situation var of 4x < v8.6.2
317
        $tableName = $wpdb->prefix.PG_CONFIG_TABLE_NAME;
318
        $query = "select * from $tableName where config='PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR_4X'";
319
        $results = $wpdb->get_results($query, ARRAY_A);
320
        if (count($results) == 0) {
321
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR_4X', 'value'  => 'default'), array('%s', '%s'));
322
        }
323
324
        //Adding WC price separator verifications to adapt extra config dynamically < v8.3.9
325
        if (!areDecimalSeparatorEqual()) {
326
            updateDecimalSeparatorDbConfig();
327
        }
328
        if (!areThousandsSeparatorEqual()) {
329
            updateThousandsSeparatorDbConfig();
330
        }
331
        
332
        //Adapting product price selector < v8.6.7
333
        $tableName = $wpdb->prefix.PG_CONFIG_TABLE_NAME;
334
        $query = "select * from $tableName where config='PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'";
335
        $results = $wpdb->get_results($query, ARRAY_A);
336
        if (count($results) == 0) {
337
            $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'));
338
        }
339
        
340
        
341
        $dbConfigs = $wpdb->get_results("select * from $tableName", ARRAY_A);
342
343
        // Convert a multiple dimension array for SQL insert statements into a simple key/value
344
        $simpleDbConfigs = array();
345
        foreach ($dbConfigs as $config) {
346
            $simpleDbConfigs[$config['config']] = $config['value'];
347
        }
348
        $newConfigs = array_diff_key($this->defaultConfigs, $simpleDbConfigs);
349
        if (!empty($newConfigs)) {
350
            foreach ($newConfigs as $key => $value) {
351
                $wpdb->insert($tableName, array('config' => $key, 'value'  => $value), array('%s', '%s'));
352
            }
353
        }
354
355
        //Current plugin config: pagantis_public_key => New field --- public_key => Old field
356
        $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

356
        $settings = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
357
358
        if (!isset($settings['pagantis_public_key']) && $settings['public_key']) {
359
            $settings['pagantis_public_key'] = $settings['public_key'];
360
            unset($settings['public_key']);
361
        }
362
363
        if (!isset($settings['pagantis_private_key']) && $settings['secret_key']) {
364
            $settings['pagantis_private_key'] = $settings['secret_key'];
365
            unset($settings['secret_key']);
366
        }
367
368
        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

368
        /** @scrutinizer ignore-call */ 
369
        update_option('woocommerce_pagantis_settings', $settings);
Loading history...
369
    }
370
371
    /**
372
     * Checks the WC settings to know if we should modify our config
373
     */
374
    public function checkWcPriceSettings()
375
    {
376
        if (!is_product() || !is_shop()) {
0 ignored issues
show
Bug introduced by
The function is_product 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

376
        if (!/** @scrutinizer ignore-call */ is_product() || !is_shop()) {
Loading history...
Bug introduced by
The function is_shop 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

376
        if (!is_product() || !/** @scrutinizer ignore-call */ is_shop()) {
Loading history...
377
            return;
378
        }
379
        $this->checkWcDecimalSeparatorSettings();
380
        $this->checkWcThousandsSeparatorSettings();
381
    }
382
383
    /**
384
     * Check woocommerce_price_thousand_sep and update our config if necessary
385
     */
386
    private function checkWcThousandsSeparatorSettings()
387
    {
388
        if (areThousandsSeparatorEqual()) {
389
            return;
390
        }
391
        if (!areThousandsSeparatorEqual()) {
392
            updateThousandsSeparatorDbConfig();
393
        }
394
    }
395
396
    /**
397
     * Check woocommerce_price_decimal_sep and update our config if necessary
398
     */
399
    private function checkWcDecimalSeparatorSettings()
400
    {
401
        if (areDecimalSeparatorEqual()) {
402
            return;
403
        }
404
405
        if (!areDecimalSeparatorEqual()) {
406
            updateDecimalSeparatorDbConfig();
407
        }
408
    }
409
410
    /**
411
     *  Pushes the simulator div depending on the config and plugin settings
412
     *
413
     * @param $template_name
414
     *
415
     * @return bool|mixed|void
416
     * @hooked woocommerce_after_template_part - 10
417
     * @see wc_get_template
418
     */
419
    public function pagantisAddSimulatorHtmlDiv($template_name)
420
    {
421
        $areSimulatorTypesValid = isSimulatorTypeValid(
422
            getConfigValue('PAGANTIS_SIMULATOR_DISPLAY_TYPE'),
423
            array('sdk.simulator.types.SELECTABLE_TEXT_CUSTOM',
424
                'sdk.simulator.types.PRODUCT_PAGE')
425
        );
426
        $isPriceTplPresent = isTemplatePresent($template_name, array('single-product/price.php'));
427
        $isAtcTplPresent = isTemplatePresent(
428
            $template_name,
429
            array('single-product/add-to-cart/variation-add-to-cart-button.php',
430
                'single-product/add-to-cart/variation.php','single-product/add-to-cart/simple.php')
431
        );
432
433
        $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

433
        $html = /** @scrutinizer ignore-call */ apply_filters('pagantis_simulator_selector_html', '<div class="mainPagantisSimulator"></div><div class="pagantisSimulator"></div>');
Loading history...
434
435
436
        $pagantisSimulator = 'enabled';
437
        if (!isPluginEnabled() || !areMerchantKeysSet() || !isSimulatorEnabled() || !isCountryShopContextValid() || !isProductAmountValid()) {
438
            $pagantisSimulator = 'disabled';
439
        }
440
441
        $pagantisSimulator4x = 'enabled';
442
        if (!isPluginEnabled4x() || !areMerchantKeysSet4x()  || !isCountryShopContextValid() || !isProductAmountValid4x()) {
443
            $pagantisSimulator4x = 'disabled';
444
        }
445
        if ($pagantisSimulator === 'disabled' && $pagantisSimulator4x === 'disabled') {
446
            return;
447
        }
448
449
        if (($areSimulatorTypesValid && $isPriceTplPresent) || (!$areSimulatorTypesValid && $isAtcTplPresent)) {
450
            self::enqueueSimulatorCss();
451
            echo $html;
452
        }
453
    }
454
455
456
    /**
457
     * Init code required to update price for products with variations
458
     *
459
     */
460
    public function pagantisAddProductSnippetForVariations()
461
    {
462
        global $product;
463
        if (!isPluginEnabled() || !areMerchantKeysSet() || !isSimulatorEnabled() || !isCountryShopContextValid() || !isProductAmountValid()) {
464
            return;
465
        }
466
467
        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

467
        /** @scrutinizer ignore-call */ 
468
        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

467
        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...
468
469
        $variationSimulatorData = array(
470
            'variationSelector' =>  $this->extraConfig['PAGANTIS_SIMULATOR_SELECTOR_VARIATION'],
471
            'productType' => $product->get_type()
472
        );
473
474
        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

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

475
        /** @scrutinizer ignore-call */ 
476
        wp_enqueue_script('pg-product-variation-simulator');
Loading history...
476
    }
477
478
    /**
479
     * @return string|void
480
     *
481
     */
482
    public function pagantisInitProductSimulator()
483
    {
484
        global $product;
485
486
        //12x
487
        $pagantisSimulator = 'enabled';
488
489
        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

489
        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

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

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

491
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
492
        if (!isPluginEnabled() || !areMerchantKeysSet() || !isSimulatorEnabled() || !isCountryShopContextValid() || !isProductAmountValid()) {
493
            $pagantisSimulator = 'disabled';
494
        }
495
496
        $pagantisSimulator4x = 'enabled';
497
        if (!isPluginEnabled4x() || !areMerchantKeysSet4x() || !isCountryShopContextValid() || !isProductAmountValid4x()) {
498
            $pagantisSimulator4x = 'disabled';
499
        }
500
501
        if ($pagantisSimulator === 'disabled' && $pagantisSimulator4x === 'disabled') {
502
            return;
503
        }
504
505
        $totalPrice = $product->get_price();
506
        $formattedInstallments = number_format($totalPrice/4, 2);
507
        $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

507
        $simulatorMessage = sprintf(/** @scrutinizer ignore-call */ __('or 4 installments of %s€, without fees, with ', 'pagantis'), $formattedInstallments);
Loading history...
508
        $post_id = $product->get_id();
509
        $simulatorData = array(
510
            'total'    => is_numeric($product->get_price()) ? $product->get_price() : 0,
511
            'public_key' => $settings['pagantis_public_key'],
512
            'simulator_type' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE'],
513
            'positionSelector' => $this->extraConfig['PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'],
514
            'positionSelector4x' => $this->extraConfig['PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR_4X'],
515
            'quantitySelector' => unserialize($this->extraConfig['PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR']),
516
            'priceSelector' => unserialize($this->extraConfig['PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR']),
517
            'totalAmount' => is_numeric($product->get_price()) ? $product->get_price() : 0,
518
            'locale' => $locale,
519
            'country' => $locale,
520
            'promoted' => $this->isPromoted($post_id),
521
            'promotedMessage' => $this->extraConfig['PAGANTIS_PROMOTION_EXTRA'],
522
            'thousandSeparator' => $this->extraConfig['PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'],
523
            'decimalSeparator' => $this->extraConfig['PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR'],
524
            'pagantisQuotesStart' => $this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS'],
525
            'pagantisSimulatorSkin' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_SKIN'],
526
            'pagantisSimulatorPosition' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION'],
527
            'finalDestination' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_SITUATION'],
528
            'variationSelector' => $this->extraConfig['PAGANTIS_SIMULATOR_SELECTOR_VARIATION'],
529
            'productType' => $product->get_type(),
530
            'pagantisSimulator' => $pagantisSimulator,
531
            'pagantisSimulator4x' => $pagantisSimulator4x,
532
            'simulatorMessage' => "$simulatorMessage <img class='mainImageLogo' alt='PAGANTIS'/>"
533
        );
534
535
        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

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

536
        /** @scrutinizer ignore-call */ 
537
        wp_enqueue_script('pg-product-simulator');
Loading history...
537
    }
538
539
    /**
540
     * Add Pagantis to payments list.
541
     *
542
     * @param $methods
543
     *
544
     * @return array
545
     */
546
    public function addPagantisGateway($methods)
547
    {
548
        if (! class_exists('WC_Payment_Gateway')) {
549
            return $methods;
550
        }
551
552
        //4x
553
        include_once('controllers/paymentController4x.php');
554
        $methods[] = 'WcPagantis4xGateway';
555
556
        //12x
557
        include_once('controllers/paymentController.php');
558
        $methods[] = 'WcPagantisGateway';
559
560
        return $methods;
561
    }
562
563
    /**
564
     * Initialize WC_Pagantis class
565
     *
566
     * @param $methods
567
     *
568
     * @return mixed
569
     */
570
    public function pagantisFilterGateways($methods)
571
    {
572
        $pagantis4x = new WcPagantis4xGateway();
573
        if (!$pagantis4x->is_available()) {
574
            unset($methods['pagantis4x']);
575
        }
576
577
        $pagantis = new WcPagantisGateway();
578
        if (!$pagantis->is_available()) {
579
            unset($methods['pagantis']);
580
        }
581
582
        return $methods;
583
    }
584
585
    /**
586
     * Add links to Plugin description
587
     *
588
     * @param $links
589
     *
590
     * @return mixed
591
     */
592
    public function pagantisActionLinks($links)
593
    {
594
        $params_array = array('page' => 'wc-settings', 'tab' => 'checkout', 'section' => 'pagantis');
595
        $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

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

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

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

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

596
        $setting_link = '<a href="'.$setting_url.'">'./** @scrutinizer ignore-call */ __('Settings', 'pagantis').'</a>';
Loading history...
597
598
        array_unshift($links, $setting_link);
599
600
        return $links;
601
    }
602
603
    /**
604
     * Add links to Plugin options
605
     *
606
     * @param $links
607
     * @param $file
608
     *
609
     * @return array
610
     */
611
    public function pagantisRowMeta($links, $file)
612
    {
613
        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

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

614
            $links[] = '<a href="'.WcPagantis::GIT_HUB_URL.'" target="_blank">'./** @scrutinizer ignore-call */ __('Documentation', 'pagantis').'</a>';
Loading history...
615
            $links[] = '<a href="'.WcPagantis::PAGANTIS_DOC_URL.'" target="_blank">'.
616
                       __('API documentation', 'pagantis').'</a>';
617
            $links[] = '<a href="'.WcPagantis::SUPPORT_EML.'">'.__('Support', 'pagantis').'</a>';
618
619
            return $links;
620
        }
621
622
        return $links;
623
    }
624
625
    /**
626
     * Read logs
627
     */
628
    public function readLogs($data)
629
    {
630
        global $wpdb;
631
        $filters   = ($data->get_params());
632
        $response  = array();
633
        $secretKey = $filters['secret'];
634
        $from = $filters['from'];
635
        $to   = $filters['to'];
636
        $cfg  = get_option('woocommerce_pagantis_settings');
0 ignored issues
show
Bug introduced by
The function get_option was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

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

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

841
        $metaProduct = /** @scrutinizer ignore-call */ get_post_meta($product_id);
Loading history...
842
        return (array_key_exists('custom_product_pagantis_promoted', $metaProduct) &&
843
                $metaProduct['custom_product_pagantis_promoted']['0'] === 'yes') ? 'true' : 'false';
844
    }
845
846
    /**
847
     * @see wp_enqueue_style
848
     */
849
    private static function enqueueSimulatorCss()
850
    {
851
        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 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

851
        wp_enqueue_style('pg_simulator_style', /** @scrutinizer ignore-call */ plugins_url('assets/css/pg-simulator-style.css', PG_WC_MAIN_FILE));
Loading history...
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

851
        /** @scrutinizer ignore-call */ 
852
        wp_enqueue_style('pg_simulator_style', plugins_url('assets/css/pg-simulator-style.css', PG_WC_MAIN_FILE));
Loading history...
852
        wp_enqueue_style('pg_sim_gfonts', 'https://fonts.googleapis.com/css?family=Open+Sans:400&display=swap');
853
    }
854
}
855
856
/**
857
 * Add widget Js
858
 **/
859
function add_pagantis_widget_js()
860
{
861
    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

861
    /** @scrutinizer ignore-call */ 
862
    wp_enqueue_script('pgSDK', 'https://cdn.pagantis.com/js/pg-v2/sdk.js', '', '', true);
Loading history...
862
}
863
864
$WcPagantis = new WcPagantis();
865