Passed
Pull Request — master (#25)
by
unknown
02:43
created

WcPagantis   F

Complexity

Total Complexity 78

Size/Duplication

Total Lines 591
Duplicated Lines 0 %

Importance

Changes 13
Bugs 0 Features 0
Metric Value
eloc 315
c 13
b 0
f 0
dl 0
loc 591
rs 2.16
wmc 78

20 Methods

Rating   Name   Duplication   Size   Complexity  
A pagantisPromotedVarSave() 0 7 2
A pagantisFilterGateways() 0 8 2
A pagantisActionLinks() 0 9 1
A pagantisRowMeta() 0 12 2
A addPagantisGateway() 0 10 2
A prepareQuantitySelector() 0 9 4
A preparePriceSelector() 0 9 4
B updateExtraConfig() 0 50 10
A pagantisPromotedProductTpl() 0 11 1
A pagantisRegisterEndpoint() 0 36 1
A __construct() 0 22 1
B readApi() 0 34 8
B pagantisAddProductSimulator() 0 30 9
A getExtraConfig() 0 11 2
A pagantisPromotedBulkTemplate() 0 3 1
A loadPagantisTranslation() 0 6 2
A isPromoted() 0 4 2
A readLogs() 0 27 5
A pagantisPromotedBulkTemplateSave() 0 11 2
D pagantisActivation() 0 104 17

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.2.2
7
 * Author: Pagantis
8
 */
9
10
//namespace Gateways;
11
12
13
if (!defined('ABSPATH')) {
14
    exit;
15
}
16
17
class WcPagantis
18
{
19
    const GIT_HUB_URL = 'https://github.com/pagantis/woocommerce';
20
    const PAGANTIS_DOC_URL = 'https://developer.pagantis.com';
21
    const SUPPORT_EML = 'mailto:[email protected]?Subject=woocommerce_plugin';
22
23
    /** Concurrency tablename */
24
    const LOGS_TABLE = 'pagantis_logs';
25
26
    /** Config tablename */
27
    const CONFIG_TABLE = 'pagantis_config';
28
29
    /** Concurrency tablename  */
30
    const CONCURRENCY_TABLE = 'pagantis_concurrency';
31
32
    /** Config tablename */
33
    const ORDERS_TABLE = 'posts';
34
35
    public $defaultConfigs = array(
36
       'PAGANTIS_TITLE'=>'Instant Financing',
37
       'PAGANTIS_SIMULATOR_DISPLAY_TYPE'=>'pgSDK.simulator.types.SIMPLE',
38
       'PAGANTIS_SIMULATOR_DISPLAY_SKIN'=>'pgSDK.simulator.skins.BLUE',
39
       'PAGANTIS_SIMULATOR_DISPLAY_POSITION'=>'hookDisplayProductButtons',
40
       'PAGANTIS_SIMULATOR_START_INSTALLMENTS'=>3,
41
       'PAGANTIS_SIMULATOR_MAX_INSTALLMENTS'=>12,
42
       'PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'=>'default',
43
       'PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION'=>'pgSDK.simulator.positions.INNER',
44
       'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'=>'a:3:{i:0;s:48:"div.summary *:not(del)>.woocommerce-Price-amount";i:1;s:54:"div.entry-summary *:not(del)>.woocommerce-Price-amount";i:2;s:36:"*:not(del)>.woocommerce-Price-amount";}',
45
       'PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'=>'a:2:{i:0;s:22:"div.quantity input.qty";i:1;s:18:"div.quantity>input";}',
46
       'PAGANTIS_FORM_DISPLAY_TYPE'=>0,
47
       'PAGANTIS_DISPLAY_MIN_AMOUNT'=>1,
48
       'PAGANTIS_URL_OK'=>'',
49
       'PAGANTIS_URL_KO'=>'',
50
       'PAGANTIS_ALLOWED_COUNTRIES' => 'a:2:{i:0;s:2:"es";i:1;s:2:"it";}',
51
       'PAGANTIS_PROMOTION_EXTRA' => '<p>Finance this product <span class="pmt-no-interest">without interest!</span></p>',
52
       'PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR' => '.',
53
       'PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR' => ','
54
    );
55
56
    /** @var Array $extraConfig */
57
    public $extraConfig;
58
59
    /**
60
     * WC_Pagantis constructor.
61
     */
62
    public function __construct()
63
    {
64
        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

64
        require_once(/** @scrutinizer ignore-call */ plugin_dir_path(__FILE__).'/vendor/autoload.php');
Loading history...
65
66
        $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...
67
68
        $this->extraConfig = $this->getExtraConfig();
69
70
        load_plugin_textdomain('pagantis', false, basename(dirname(__FILE__)).'/languages');
0 ignored issues
show
Bug introduced by
The function load_plugin_textdomain was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

71
        /** @scrutinizer ignore-call */ 
72
        add_filter('woocommerce_payment_gateways', array($this, 'addPagantisGateway'));
Loading history...
72
        add_filter('woocommerce_available_payment_gateways', array($this, 'pagantisFilterGateways'), 9999);
73
        add_filter('plugin_row_meta', array($this, 'pagantisRowMeta'), 10, 2);
74
        add_filter('plugin_action_links_'.plugin_basename(__FILE__), array($this, 'pagantisActionLinks'));
0 ignored issues
show
Bug introduced by
The function plugin_basename was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

74
        add_filter('plugin_action_links_'./** @scrutinizer ignore-call */ plugin_basename(__FILE__), array($this, 'pagantisActionLinks'));
Loading history...
75
        add_action('woocommerce_after_add_to_cart_form', array($this, 'pagantisAddProductSimulator'));
0 ignored issues
show
Bug introduced by
The function add_action was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

75
        /** @scrutinizer ignore-call */ 
76
        add_action('woocommerce_after_add_to_cart_form', array($this, 'pagantisAddProductSimulator'));
Loading history...
76
        add_action('wp_enqueue_scripts', 'add_pagantis_widget_js');
77
        add_action('rest_api_init', array($this, 'pagantisRegisterEndpoint')); //Endpoint
78
        add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
79
        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

79
        /** @scrutinizer ignore-call */ 
80
        register_activation_hook(__FILE__, array($this, 'pagantisActivation'));
Loading history...
80
        add_action('woocommerce_product_options_general_product_data', array($this, 'pagantisPromotedProductTpl'));
81
        add_action('woocommerce_process_product_meta', array($this, 'pagantisPromotedVarSave'));
82
        add_action('woocommerce_product_bulk_edit_start', array($this,'pagantisPromotedBulkTemplate'));
83
        add_action('woocommerce_product_bulk_edit_save', array($this,'pagantisPromotedBulkTemplateSave'));
84
    }
85
86
    /**
87
     * Piece of html code to insert into BULK admin edit
88
     */
89
    public function pagantisPromotedBulkTemplate()
90
    {
91
        echo '<div class="inline-edit-group">
92
			<label class="alignleft">
93
				<span class="title">Pagantis promoted</span>
94
				<span class="input-text-wrap">
95
                    <input type="checkbox" id="pagantis_promoted" name="pagantis_promoted"/>
96
				</span>
97
			</label>
98
		</div>';
99
    }
100
101
    /**
102
     * Php code to save our meta after a bulk admin edit
103
     * @param $product
104
     */
105
    public function pagantisPromotedBulkTemplateSave($product)
106
    {
107
        $post_id = $product->get_id();
108
        $pagantis_promoted_value = $_REQUEST['pagantis_promoted'];
109
        if ($pagantis_promoted_value == 'on') {
110
            $pagantis_promoted_value = 'yes';
111
        } else {
112
            $pagantis_promoted_value = 'no';
113
        }
114
115
        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

115
        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

115
        /** @scrutinizer ignore-call */ 
116
        update_post_meta($post_id, 'custom_product_pagantis_promoted', esc_attr($pagantis_promoted_value));
Loading history...
116
    }
117
118
    /**
119
     * Piece of html code to insert into PRODUCT admin edit
120
     */
121
    public function pagantisPromotedProductTpl()
122
    {
123
        global $post;
124
        $_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

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

125
        /** @scrutinizer ignore-call */ 
126
        woocommerce_wp_checkbox(
Loading history...
126
            array(
127
                'id' => 'pagantis_promoted',
128
                '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

128
                'label' => /** @scrutinizer ignore-call */ __('Pagantis promoted', 'woocommerce'),
Loading history...
129
                'value' => $_product['custom_product_pagantis_promoted']['0'],
130
                'cbvalue' => 'yes',
131
                'echo' => true
132
            )
133
        );
134
    }
135
136
    /**
137
     *  Php code to save our meta after a PRODUCT admin edit
138
     * @param $post_id
139
     */
140
    public function pagantisPromotedVarSave($post_id)
141
    {
142
        $pagantis_promoted_value = $_POST['pagantis_promoted'];
143
        if ($pagantis_promoted_value == null) {
144
            $pagantis_promoted_value = 'no';
145
        }
146
        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

146
        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

146
        /** @scrutinizer ignore-call */ 
147
        update_post_meta($post_id, 'custom_product_pagantis_promoted', esc_attr($pagantis_promoted_value));
Loading history...
147
    }
148
149
    /*
150
     * Replace 'textdomain' with your plugin's textdomain. e.g. 'woocommerce'.
151
     * File to be named, for example, yourtranslationfile-en_GB.mo
152
     * File to be placed, for example, wp-content/lanaguages/textdomain/yourtranslationfile-en_GB.mo
153
     */
154
    public function loadPagantisTranslation($mofile, $domain)
155
    {
156
        if ('pagantis' === $domain) {
157
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . get_locale() . '.mo';
0 ignored issues
show
Bug introduced by
The constant WP_LANG_DIR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The function get_locale was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

157
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . /** @scrutinizer ignore-call */ get_locale() . '.mo';
Loading history...
158
        }
159
        return $mofile;
160
    }
161
162
    /**
163
     * Sql table
164
     */
165
    public function pagantisActivation()
166
    {
167
        global $wpdb;
168
169
        $tableName = $wpdb->prefix.self::CONCURRENCY_TABLE;
170
        if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName) {
171
            $charset_collate = $wpdb->get_charset_collate();
172
            $sql = "CREATE TABLE $tableName ( order_id int NOT NULL,  
173
                    createdAt timestamp DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY id (order_id)) $charset_collate";
174
            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...
175
            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

175
            /** @scrutinizer ignore-call */ 
176
            dbDelta($sql);
Loading history...
176
        }
177
178
        $tableName = $wpdb->prefix.self::CONFIG_TABLE;
179
180
        //Check if table exists
181
        $tableExists = $wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName;
182
        if ($tableExists) {
183
            $charset_collate = $wpdb->get_charset_collate();
184
            $sql = "CREATE TABLE IF NOT EXISTS $tableName (
185
                                id int NOT NULL AUTO_INCREMENT, 
186
                                config varchar(60) NOT NULL, 
187
                                value varchar(1000) NOT NULL, 
188
                                UNIQUE KEY id(id)) $charset_collate";
189
190
            require_once(ABSPATH.'wp-admin/includes/upgrade.php');
191
            dbDelta($sql);
192
        } else {
193
            //Updated value field to adapt to new length < v8.0.1
194
            $query = "select COLUMN_TYPE FROM information_schema.COLUMNS where TABLE_NAME='$tableName' AND COLUMN_NAME='value'";
195
            $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...
196
            if ($results['0']['COLUMN_TYPE'] == 'varchar(100)') {
197
                $sql = "ALTER TABLE $tableName MODIFY value varchar(1000)";
198
                $wpdb->query($sql);
199
            }
200
201
            //Adapting selector to array < v8.1.1
202
            $query = "select * from $tableName where config='PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR' 
203
                               or config='PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'";
204
            $dbCurrentConfig = $wpdb->get_results($query, ARRAY_A);
205
            foreach ($dbCurrentConfig as $item) {
206
                if ($item['config'] == 'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR') {
207
                    $css_price_selector = $this->preparePriceSelector($item['value']);
208
                    if ($item['value'] != $css_price_selector) {
209
                        $wpdb->update(
210
                            $tableName,
211
                            array('value' => stripslashes($css_price_selector)),
212
                            array('config' => 'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'),
213
                            array('%s'),
214
                            array('%s')
215
                        );
216
                    }
217
                } elseif ($item['config'] == 'PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR') {
218
                    $css_quantity_selector = $this->prepareQuantitySelector($item['value']);
219
                    if ($item['value'] != $css_quantity_selector) {
220
                        $wpdb->update(
221
                            $tableName,
222
                            array('value' => stripslashes($css_quantity_selector)),
223
                            array('config' => 'PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'),
224
                            array('%s'),
225
                            array('%s')
226
                        );
227
                    }
228
                }
229
            }
230
        }
231
232
        //Adapting selector to array < v8.2.2
233
        $tableName = $wpdb->prefix.self::CONFIG_TABLE;
234
        $query = "select * from $tableName where config='PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'";
235
        $results = $wpdb->get_results($query, ARRAY_A);
236
        if (count($results) == 0) {
237
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR', 'value'  => '.'), array('%s', '%s'));
238
            $wpdb->insert($tableName, array('config' => 'PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR', 'value'  => ','), array('%s', '%s'));
239
        }
240
241
        $dbConfigs = $wpdb->get_results("select * from $tableName", ARRAY_A);
242
243
        // Convert a multimple dimension array for SQL insert statements into a simple key/value
244
        $simpleDbConfigs = array();
245
        foreach ($dbConfigs as $config) {
246
            $simpleDbConfigs[$config['config']] = $config['value'];
247
        }
248
        $newConfigs = array_diff_key($this->defaultConfigs, $simpleDbConfigs);
249
        if (!empty($newConfigs)) {
250
            foreach ($newConfigs as $key => $value) {
251
                $wpdb->insert($tableName, array('config' => $key, 'value'  => $value), array('%s', '%s'));
252
            }
253
        }
254
255
        //Current plugin config: pagantis_public_key => New field --- public_key => Old field
256
        $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

256
        $settings = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
257
258
        if (!isset($settings['pagantis_public_key']) && $settings['public_key']) {
259
            $settings['pagantis_public_key'] = $settings['public_key'];
260
            unset($settings['public_key']);
261
        }
262
263
        if (!isset($settings['pagantis_private_key']) && $settings['secret_key']) {
264
            $settings['pagantis_private_key'] = $settings['secret_key'];
265
            unset($settings['secret_key']);
266
        }
267
268
        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

268
        /** @scrutinizer ignore-call */ 
269
        update_option('woocommerce_pagantis_settings', $settings);
Loading history...
269
    }
270
271
    /**
272
     * Product simulator
273
     */
274
    public function pagantisAddProductSimulator()
275
    {
276
        global $product;
277
278
        $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

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

279
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
280
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
281
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
282
        if ($cfg['enabled'] !== 'yes' || $cfg['pagantis_public_key'] == '' || $cfg['pagantis_private_key'] == '' ||
283
            $cfg['simulator'] !== 'yes' ||  $product->price < $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'] ||
284
            !$allowedCountry ) {
285
            return;
286
        }
287
288
        $post_id = $product->get_id();
289
        $template_fields = array(
290
            'total'    => is_numeric($product->price) ? $product->price : 0,
291
            'public_key' => $cfg['pagantis_public_key'],
292
            'simulator_type' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE'],
293
            'positionSelector' => $this->extraConfig['PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'],
294
            'quantitySelector' => unserialize($this->extraConfig['PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR']),
295
            'priceSelector' => unserialize($this->extraConfig['PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR']),
296
            'totalAmount' => is_numeric($product->price) ? $product->price : 0,
297
            'locale' => $locale,
298
            'promoted' => $this->isPromoted($post_id),
299
            'promotedMessage' => $this->extraConfig['PAGANTIS_PROMOTION_EXTRA'],
300
            'thousandSeparator' => $this->extraConfig['PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'],
301
            'decimalSeparator' => $this->extraConfig['PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR']
302
        );
303
        wc_get_template('product_simulator.php', $template_fields, '', $this->template_path);
0 ignored issues
show
Bug introduced by
The function wc_get_template was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

303
        /** @scrutinizer ignore-call */ 
304
        wc_get_template('product_simulator.php', $template_fields, '', $this->template_path);
Loading history...
304
    }
305
306
    /**
307
     * Add Pagantis to payments list.
308
     *
309
     * @param $methods
310
     *
311
     * @return array
312
     */
313
    public function addPagantisGateway($methods)
314
    {
315
        if (! class_exists('WC_Payment_Gateway')) {
316
            return $methods;
317
        }
318
319
        include_once('controllers/paymentController.php');
320
        $methods[] = 'WcPagantisGateway';
321
322
        return $methods;
323
    }
324
325
    /**
326
     * Initialize WC_Pagantis class
327
     *
328
     * @param $methods
329
     *
330
     * @return mixed
331
     */
332
    public function pagantisFilterGateways($methods)
333
    {
334
        $pagantis = new WcPagantisGateway();
335
        if (!$pagantis->is_available()) {
336
            unset($methods['pagantis']);
337
        }
338
339
        return $methods;
340
    }
341
342
    /**
343
     * Add links to Plugin description
344
     *
345
     * @param $links
346
     *
347
     * @return mixed
348
     */
349
    public function pagantisActionLinks($links)
350
    {
351
        $params_array = array('page' => 'wc-settings', 'tab' => 'checkout', 'section' => 'pagantis');
352
        $setting_url  = esc_url(add_query_arg($params_array, admin_url('admin.php?')));
0 ignored issues
show
Bug introduced by
The function admin_url was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

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

353
        $setting_link = '<a href="'.$setting_url.'">'./** @scrutinizer ignore-call */ __('Settings', 'pagantis').'</a>';
Loading history...
354
355
        array_unshift($links, $setting_link);
356
357
        return $links;
358
    }
359
360
    /**
361
     * Add links to Plugin options
362
     *
363
     * @param $links
364
     * @param $file
365
     *
366
     * @return array
367
     */
368
    public function pagantisRowMeta($links, $file)
369
    {
370
        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

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

371
            $links[] = '<a href="'.WcPagantis::GIT_HUB_URL.'" target="_blank">'./** @scrutinizer ignore-call */ __('Documentation', 'pagantis').'</a>';
Loading history...
372
            $links[] = '<a href="'.WcPagantis::PAGANTIS_DOC_URL.'" target="_blank">'.
373
                       __('API documentation', 'pagantis').'</a>';
374
            $links[] = '<a href="'.WcPagantis::SUPPORT_EML.'">'.__('Support', 'pagantis').'</a>';
375
376
            return $links;
377
        }
378
379
        return $links;
380
    }
381
382
    /**
383
     * Read logs
384
     */
385
    public function readLogs($data)
386
    {
387
        global $wpdb;
388
        $filters   = ($data->get_params());
389
        $response  = array();
390
        $secretKey = $filters['secret'];
391
        $from = $filters['from'];
392
        $to   = $filters['to'];
393
        $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

393
        $cfg  = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
394
        $privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
395
        $tableName = $wpdb->prefix.self::LOGS_TABLE;
396
        $query = "select * from $tableName where createdAt>$from and createdAt<$to order by createdAt desc";
397
        $results = $wpdb->get_results($query);
398
        if (isset($results) && $privateKey == $secretKey) {
399
            foreach ($results as $key => $result) {
400
                $response[$key]['timestamp'] = $result->createdAt;
401
                $response[$key]['log']       = json_decode($result->log);
402
            }
403
        } else {
404
            $response['result'] = 'Error';
405
        }
406
        $response = json_encode($response);
407
        header("HTTP/1.1 200", true, 200);
408
        header('Content-Type: application/json', true);
409
        header('Content-Length: '.strlen($response));
410
        echo($response);
411
        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...
412
    }
413
414
    /**
415
     * Update extra config
416
     */
417
    public function updateExtraConfig($data)
418
    {
419
        global $wpdb;
420
        $tableName = $wpdb->prefix.self::CONFIG_TABLE;
421
        $response = array('status'=>null);
422
423
        $filters   = ($data->get_params());
424
        $secretKey = $filters['secret'];
425
        $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

425
        $cfg  = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
426
        $privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
427
        if ($privateKey != $secretKey) {
428
            $response['status'] = 401;
429
            $response['result'] = 'Unauthorized';
430
        } elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
431
            if (count($_POST)) {
432
                foreach ($_POST as $config => $value) {
433
                    if (isset($this->defaultConfigs[$config]) && $response['status']==null) {
434
                        $wpdb->update(
435
                            $tableName,
436
                            array('value' => stripslashes($value)),
437
                            array('config' => $config),
438
                            array('%s'),
439
                            array('%s')
440
                        );
441
                    } else {
442
                        $response['status'] = 400;
443
                        $response['result'] = 'Bad request';
444
                    }
445
                }
446
            } else {
447
                $response['status'] = 422;
448
                $response['result'] = 'Empty data';
449
            }
450
        }
451
452
        if ($response['status']==null) {
453
            $tableName = $wpdb->prefix.self::CONFIG_TABLE;
454
            $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...
455
            foreach ($dbResult as $value) {
456
                $formattedResult[$value['config']] = $value['value'];
457
            }
458
            $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 455. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
459
        }
460
461
        $result = json_encode($response['result']);
462
        header("HTTP/1.1 ".$response['status'], true, $response['status']);
463
        header('Content-Type: application/json', true);
464
        header('Content-Length: '.strlen($result));
465
        echo($result);
466
        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...
467
    }
468
469
    /**
470
     * Read logs
471
     */
472
    public function readApi($data)
473
    {
474
        global $wpdb;
475
        $filters   = ($data->get_params());
476
        $response  = array('timestamp'=>time());
477
        $secretKey = $filters['secret'];
478
        $from = ($filters['from']) ? date_create($filters['from']) : date("Y-m-d", strtotime("-7 day"));
479
        $to = ($filters['to']) ? date_create($filters['to']) : date("Y-m-d", strtotime("+1 day"));
480
        $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...
481
        $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

481
        $cfg  = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
482
        $privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
483
        $tableName = $wpdb->prefix.self::ORDERS_TABLE;
484
        $tableNameInner = $wpdb->prefix.'postmeta';
485
        $query = "select * from $tableName tn INNER JOIN $tableNameInner tn2 ON tn2.post_id = tn.id
486
                  where tn.post_type='shop_order' and tn.post_date>'".$from->format("Y-m-d")."' 
487
                  and tn.post_date<'".$to->format("Y-m-d")."' order by tn.post_date desc";
488
        $results = $wpdb->get_results($query);
489
490
        if (isset($results) && $privateKey == $secretKey) {
491
            foreach ($results as $result) {
492
                $key = $result->ID;
493
                $response['message'][$key]['timestamp'] = $result->post_date;
494
                $response['message'][$key]['order_id'] = $key;
495
                $response['message'][$key][$result->meta_key] = $result->meta_value;
496
            }
497
        } else {
498
            $response['result'] = 'Error';
499
        }
500
        $response = json_encode($response);
501
        header("HTTP/1.1 200", true, 200);
502
        header('Content-Type: application/json', true);
503
        header('Content-Length: '.strlen($response));
504
        echo($response);
505
        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...
506
    }
507
508
    /**
509
     * ENDPOINT - Read logs -> Hook: rest_api_init
510
     * @return mixed
511
     */
512
    public function pagantisRegisterEndpoint()
513
    {
514
        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

514
        /** @scrutinizer ignore-call */ 
515
        register_rest_route(
Loading history...
515
            'pagantis/v1',
516
            '/logs/(?P<secret>\w+)/(?P<from>\d+)/(?P<to>\d+)',
517
            array(
518
                'methods'  => 'GET',
519
                'callback' => array(
520
                    $this,
521
                    'readLogs')
522
            ),
523
            true
524
        );
525
526
        register_rest_route(
527
            'pagantis/v1',
528
            '/configController/(?P<secret>\w+)',
529
            array(
530
                'methods'  => 'GET, POST',
531
                'callback' => array(
532
                    $this,
533
                    'updateExtraConfig')
534
            ),
535
            true
536
        );
537
538
        register_rest_route(
539
            'pagantis/v1',
540
            '/api/(?P<secret>\w+)/(?P<from>\w+)/(?P<to>\w+)',
541
            array(
542
                'methods'  => 'GET',
543
                'callback' => array(
544
                    $this,
545
                    'readApi')
546
            ),
547
            true
548
        );
549
    }
550
551
    /**
552
     * @return array
553
     */
554
    private function getExtraConfig()
555
    {
556
        global $wpdb;
557
        $tableName = $wpdb->prefix.self::CONFIG_TABLE;
558
        $response = array();
559
        $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...
560
        foreach ($dbResult as $value) {
561
            $response[$value['config']] = $value['value'];
562
        }
563
564
        return $response;
565
    }
566
567
    /**
568
     * @param $css_quantity_selector
569
     *
570
     * @return mixed|string
571
     */
572
    private function prepareQuantitySelector($css_quantity_selector)
573
    {
574
        if ($css_quantity_selector == 'default' || $css_quantity_selector == '') {
575
            $css_quantity_selector = $this->defaultConfigs['PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'];
576
        } elseif (!unserialize($css_quantity_selector)) { //in the case of a custom string selector, we keep it
577
            $css_quantity_selector = serialize(array($css_quantity_selector));
578
        }
579
580
        return $css_quantity_selector;
581
    }
582
583
    /**
584
     * @param $css_price_selector
585
     *
586
     * @return mixed|string
587
     */
588
    private function preparePriceSelector($css_price_selector)
589
    {
590
        if ($css_price_selector == 'default' || $css_price_selector == '') {
591
            $css_price_selector = $this->defaultConfigs['PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'];
592
        } elseif (!unserialize($css_price_selector)) { //in the case of a custom string selector, we keep it
593
            $css_price_selector = serialize(array($css_price_selector));
594
        }
595
596
        return $css_price_selector;
597
    }
598
599
    /**
600
     * @param $product_id
601
     *
602
     * @return string
603
     */
604
    private function isPromoted($product_id)
605
    {
606
        $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

606
        $metaProduct = /** @scrutinizer ignore-call */ get_post_meta($product_id);
Loading history...
607
        return ($metaProduct['custom_product_pagantis_promoted']['0'] === 'yes') ? 'true' : 'false';
608
    }
609
}
610
611
/**
612
 * Add widget Js
613
 **/
614
function add_pagantis_widget_js()
615
{
616
    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

616
    /** @scrutinizer ignore-call */ 
617
    wp_enqueue_script('pgSDK', 'https://cdn.pagantis.com/js/pg-v2/sdk.js', '', '', true);
Loading history...
617
    wp_enqueue_script('pmtSDK', 'https://cdn.pagamastarde.com/js/pmt-v2/sdk.js', '', '', true);
618
}
619
620
$WcPagantis = new WcPagantis();
621