Completed
Push — master ( 7a2686...3cd1d2 )
by pablo
15s queued 14s
created

WcPagantis::pagantisActivation()   F

Complexity

Conditions 18
Paths 384

Size

Total Lines 112
Code Lines 70

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 18
eloc 70
c 4
b 0
f 0
nc 384
nop 0
dl 0
loc 112
rs 1.7333

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Plugin Name: Pagantis
4
 * Plugin URI: http://www.pagantis.com/
5
 * Description: Financiar con Pagantis
6
 * Version: 8.3.0
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'=>'Pago en cuotas',
37
       'PAGANTIS_SIMULATOR_DISPLAY_TYPE'=>'sdk.simulator.types.SELECTABLE_TEXT_CUSTOM',
38
       'PAGANTIS_SIMULATOR_DISPLAY_SKIN'=>'sdk.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'=>'sdk.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_DISPLAY_MAX_AMOUNT'=>0,
49
       'PAGANTIS_URL_OK'=>'',
50
       'PAGANTIS_URL_KO'=>'',
51
       'PAGANTIS_ALLOWED_COUNTRIES' => 'a:3:{i:0;s:2:"es";i:1;s:2:"it";i:2;s:2:"fr";}',
52
       'PAGANTIS_PROMOTION_EXTRA' => '<p>Finance this product <span class="pg-no-interest">without interest!</span></p>',
53
       'PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR' => '.',
54
       'PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR' => ','
55
    );
56
57
    /** @var Array $extraConfig */
58
    public $extraConfig;
59
60
    /**
61
     * WC_Pagantis constructor.
62
     */
63
    public function __construct()
64
    {
65
        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

65
        require_once(/** @scrutinizer ignore-call */ plugin_dir_path(__FILE__).'/vendor/autoload.php');
Loading history...
66
67
        $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...
68
69
        $this->extraConfig = $this->getExtraConfig();
70
71
        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

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

72
        /** @scrutinizer ignore-call */ 
73
        add_filter('woocommerce_payment_gateways', array($this, 'addPagantisGateway'));
Loading history...
73
        add_filter('woocommerce_available_payment_gateways', array($this, 'pagantisFilterGateways'), 9999);
74
        add_filter('plugin_row_meta', array($this, 'pagantisRowMeta'), 10, 2);
75
        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

75
        add_filter('plugin_action_links_'./** @scrutinizer ignore-call */ plugin_basename(__FILE__), array($this, 'pagantisActionLinks'));
Loading history...
76
        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

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

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

116
        /** @scrutinizer ignore-call */ 
117
        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

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

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

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

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

147
        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

147
        /** @scrutinizer ignore-call */ 
148
        update_post_meta($post_id, 'custom_product_pagantis_promoted', esc_attr($pagantis_promoted_value));
Loading history...
148
    }
149
150
    /*
151
     * Replace 'textdomain' with your plugin's textdomain. e.g. 'woocommerce'.
152
     * File to be named, for example, yourtranslationfile-en_GB.mo
153
     * File to be placed, for example, wp-content/lanaguages/textdomain/yourtranslationfile-en_GB.mo
154
     */
155
    public function loadPagantisTranslation($mofile, $domain)
156
    {
157
        if ('pagantis' === $domain) {
158
            $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

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

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

265
        $settings = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
266
267
        if (!isset($settings['pagantis_public_key']) && $settings['public_key']) {
268
            $settings['pagantis_public_key'] = $settings['public_key'];
269
            unset($settings['public_key']);
270
        }
271
272
        if (!isset($settings['pagantis_private_key']) && $settings['secret_key']) {
273
            $settings['pagantis_private_key'] = $settings['secret_key'];
274
            unset($settings['secret_key']);
275
        }
276
277
        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

277
        /** @scrutinizer ignore-call */ 
278
        update_option('woocommerce_pagantis_settings', $settings);
Loading history...
278
    }
279
280
    /**
281
     * Product simulator
282
     */
283
    public function pagantisAddProductSimulator()
284
    {
285
        global $product;
286
287
        $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

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

288
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
289
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
290
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
291
        $minAmount = $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'];
292
        $maxAmount = $this->extraConfig['PAGANTIS_DISPLAY_MAX_AMOUNT'];
293
        $totalPrice = $product->get_price();
294
        $validAmount = ($totalPrice>=$minAmount && ($totalPrice<=$maxAmount || $maxAmount=='0'));
295
        if ($cfg['enabled'] !== 'yes' || $cfg['pagantis_public_key'] == '' || $cfg['pagantis_private_key'] == '' ||
296
            $cfg['simulator'] !== 'yes'  || !$allowedCountry || !$validAmount) {
297
            return;
298
        }
299
300
        $post_id = $product->get_id();
301
        $template_fields = array(
302
            'total'    => is_numeric($product->price) ? $product->price : 0,
303
            'public_key' => $cfg['pagantis_public_key'],
304
            'simulator_type' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE'],
305
            'positionSelector' => $this->extraConfig['PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'],
306
            'quantitySelector' => unserialize($this->extraConfig['PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR']),
307
            'priceSelector' => unserialize($this->extraConfig['PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR']),
308
            'totalAmount' => is_numeric($product->get_price()) ? $product->get_price() : 0,
309
            'locale' => $locale,
310
            'country' => $locale,
311
            'promoted' => $this->isPromoted($post_id),
312
            'promotedMessage' => $this->extraConfig['PAGANTIS_PROMOTION_EXTRA'],
313
            'thousandSeparator' => $this->extraConfig['PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'],
314
            'decimalSeparator' => $this->extraConfig['PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR'],
315
            'pagantisQuotesStart' => $this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS'],
316
            'pagantisSimulatorSkin' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_SKIN'],
317
            'pagantisSimulatorPosition' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION'],
318
            'separator' => __('ó', 'pagantis')
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

318
            'separator' => /** @scrutinizer ignore-call */ __('ó', 'pagantis')
Loading history...
319
        );
320
        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

320
        /** @scrutinizer ignore-call */ 
321
        wc_get_template('product_simulator.php', $template_fields, '', $this->template_path);
Loading history...
321
    }
322
323
    /**
324
     * Add Pagantis to payments list.
325
     *
326
     * @param $methods
327
     *
328
     * @return array
329
     */
330
    public function addPagantisGateway($methods)
331
    {
332
        if (! class_exists('WC_Payment_Gateway')) {
333
            return $methods;
334
        }
335
336
        include_once('controllers/paymentController.php');
337
        $methods[] = 'WcPagantisGateway';
338
339
        return $methods;
340
    }
341
342
    /**
343
     * Initialize WC_Pagantis class
344
     *
345
     * @param $methods
346
     *
347
     * @return mixed
348
     */
349
    public function pagantisFilterGateways($methods)
350
    {
351
        $pagantis = new WcPagantisGateway();
352
        if (!$pagantis->is_available()) {
353
            unset($methods['pagantis']);
354
        }
355
356
        return $methods;
357
    }
358
359
    /**
360
     * Add links to Plugin description
361
     *
362
     * @param $links
363
     *
364
     * @return mixed
365
     */
366
    public function pagantisActionLinks($links)
367
    {
368
        $params_array = array('page' => 'wc-settings', 'tab' => 'checkout', 'section' => 'pagantis');
369
        $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

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

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

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

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

370
        $setting_link = '<a href="'.$setting_url.'">'./** @scrutinizer ignore-call */ __('Settings', 'pagantis').'</a>';
Loading history...
371
372
        array_unshift($links, $setting_link);
373
374
        return $links;
375
    }
376
377
    /**
378
     * Add links to Plugin options
379
     *
380
     * @param $links
381
     * @param $file
382
     *
383
     * @return array
384
     */
385
    public function pagantisRowMeta($links, $file)
386
    {
387
        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

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

388
            $links[] = '<a href="'.WcPagantis::GIT_HUB_URL.'" target="_blank">'./** @scrutinizer ignore-call */ __('Documentation', 'pagantis').'</a>';
Loading history...
389
            $links[] = '<a href="'.WcPagantis::PAGANTIS_DOC_URL.'" target="_blank">'.
390
                       __('API documentation', 'pagantis').'</a>';
391
            $links[] = '<a href="'.WcPagantis::SUPPORT_EML.'">'.__('Support', 'pagantis').'</a>';
392
393
            return $links;
394
        }
395
396
        return $links;
397
    }
398
399
    /**
400
     * Read logs
401
     */
402
    public function readLogs($data)
403
    {
404
        global $wpdb;
405
        $filters   = ($data->get_params());
406
        $response  = array();
407
        $secretKey = $filters['secret'];
408
        $from = $filters['from'];
409
        $to   = $filters['to'];
410
        $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

410
        $cfg  = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
411
        $privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
412
        $tableName = $wpdb->prefix.self::LOGS_TABLE;
413
        $query = "select * from $tableName where createdAt>$from and createdAt<$to order by createdAt desc";
414
        $results = $wpdb->get_results($query);
415
        if (isset($results) && $privateKey == $secretKey) {
416
            foreach ($results as $key => $result) {
417
                $response[$key]['timestamp'] = $result->createdAt;
418
                $response[$key]['log']       = json_decode($result->log);
419
            }
420
        } else {
421
            $response['result'] = 'Error';
422
        }
423
        $response = json_encode($response);
424
        header("HTTP/1.1 200", true, 200);
425
        header('Content-Type: application/json', true);
426
        header('Content-Length: '.strlen($response));
427
        echo($response);
428
        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...
429
    }
430
431
    /**
432
     * Update extra config
433
     */
434
    public function updateExtraConfig($data)
435
    {
436
        global $wpdb;
437
        $tableName = $wpdb->prefix.self::CONFIG_TABLE;
438
        $response = array('status'=>null);
439
440
        $filters   = ($data->get_params());
441
        $secretKey = $filters['secret'];
442
        $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

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

498
        $cfg  = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
499
        $privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
500
        $tableName = $wpdb->prefix.self::ORDERS_TABLE;
501
        $tableNameInner = $wpdb->prefix.'postmeta';
502
        $query = "select * from $tableName tn INNER JOIN $tableNameInner tn2 ON tn2.post_id = tn.id
503
                  where tn.post_type='shop_order' and tn.post_date>'".$from->format("Y-m-d")."' 
504
                  and tn.post_date<'".$to->format("Y-m-d")."' order by tn.post_date desc";
505
        $results = $wpdb->get_results($query);
506
507
        if (isset($results) && $privateKey == $secretKey) {
508
            foreach ($results as $result) {
509
                $key = $result->ID;
510
                $response['message'][$key]['timestamp'] = $result->post_date;
511
                $response['message'][$key]['order_id'] = $key;
512
                $response['message'][$key][$result->meta_key] = $result->meta_value;
513
            }
514
        } else {
515
            $response['result'] = 'Error';
516
        }
517
        $response = json_encode($response);
518
        header("HTTP/1.1 200", true, 200);
519
        header('Content-Type: application/json', true);
520
        header('Content-Length: '.strlen($response));
521
        echo($response);
522
        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...
523
    }
524
525
    /**
526
     * ENDPOINT - Read logs -> Hook: rest_api_init
527
     * @return mixed
528
     */
529
    public function pagantisRegisterEndpoint()
530
    {
531
        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

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

623
        $metaProduct = /** @scrutinizer ignore-call */ get_post_meta($product_id);
Loading history...
624
        return (array_key_exists('custom_product_pagantis_promoted', $metaProduct) &&
625
                $metaProduct['custom_product_pagantis_promoted']['0'] === 'yes') ? 'true' : 'false';
626
    }
627
}
628
629
/**
630
 * Add widget Js
631
 **/
632
function add_pagantis_widget_js()
633
{
634
    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

634
    /** @scrutinizer ignore-call */ 
635
    wp_enqueue_script('pgSDK', 'https://cdn.pagantis.com/js/pg-v2/sdk.js', '', '', true);
Loading history...
635
}
636
637
$WcPagantis = new WcPagantis();
638