Completed
Push — master ( f604f3...51997e )
by
unknown
14s queued 10s
created

WcPagantis::pagantisActivation()   D

Complexity

Conditions 17
Paths 192

Size

Total Lines 104
Code Lines 65

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 17
eloc 65
c 4
b 0
f 0
nc 192
nop 0
dl 0
loc 104
rs 4.45

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.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'=>'sdk.simulator.types.SIMPLE',
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_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
            'pagantisQuotesStart' => $this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS'],
303
            'pagantisSimulatorSkin' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_SKIN'],
304
            'pagantisSimulatorPosition' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION']
305
        );
306
        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

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

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

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

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

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

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

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

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

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

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

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

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

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

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