Passed
Pull Request — master (#47)
by pablo
04:23
created

WcPagantis::loadPagantisTranslation()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 7
rs 10
1
<?php
2
/**
3
 * Plugin Name: Pagantis
4
 * Plugin URI: http://www.pagantis.com/
5
 * Description: Financiar con Pagantis
6
 * Version: 8.3.6
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.PRODUCT_PAGE',
38
        'PAGANTIS_SIMULATOR_DISPLAY_TYPE_CHECKOUT' => 'sdk.simulator.types.CHECKOUT_PAGE',
39
        'PAGANTIS_SIMULATOR_DISPLAY_SKIN'          => 'sdk.simulator.skins.BLUE',
40
        'PAGANTIS_SIMULATOR_DISPLAY_POSITION'      => 'hookDisplayProductButtons',
41
        'PAGANTIS_SIMULATOR_START_INSTALLMENTS'    => 3,
42
        'PAGANTIS_SIMULATOR_MAX_INSTALLMENTS'      => 12,
43
        'PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR' => 'default',
44
        'PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION'  => 'sdk.simulator.positions.INNER',
45
        '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";}',
46
        'PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR' => 'a:2:{i:0;s:22:"div.quantity input.qty";i:1;s:18:"div.quantity>input";}',
47
        'PAGANTIS_FORM_DISPLAY_TYPE'               => 0,
48
        'PAGANTIS_DISPLAY_MIN_AMOUNT'              => 1,
49
        'PAGANTIS_DISPLAY_MAX_AMOUNT'              => 0,
50
        'PAGANTIS_URL_OK'                          => '',
51
        'PAGANTIS_URL_KO'                          => '',
52
        'PAGANTIS_ALLOWED_COUNTRIES'               => 'a:3:{i:0;s:2:"es";i:1;s:2:"it";i:2;s:2:"fr";}',
53
        'PAGANTIS_PROMOTION_EXTRA'                 => '<p>Finance this product <span class="pg-no-interest">without interest!</span></p>',
54
        'PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'   => '.',
55
        'PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR'     => ',',
56
        'PAGANTIS_SIMULATOR_DISPLAY_SITUATION'     => 'default',
57
        'PAGANTIS_SIMULATOR_SELECTOR_VARIATION'    => 'default'
58
    );
59
60
    /** @var Array $extraConfig */
61
    public $extraConfig;
62
63
    /**
64
     * WC_Pagantis constructor.
65
     */
66
    public function __construct()
67
    {
68
        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

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

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

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

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

81
        /** @scrutinizer ignore-call */ 
82
        add_action('woocommerce_after_add_to_cart_form', array($this, 'pagantisAddProductSimulator'));
Loading history...
82
        add_action('wp_enqueue_scripts', 'add_pagantis_widget_js');
83
        add_action('rest_api_init', array($this, 'pagantisRegisterEndpoint')); //Endpoint
84
        add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
85
        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

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

122
        /** @scrutinizer ignore-call */ 
123
        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

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

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

132
        /** @scrutinizer ignore-call */ 
133
        woocommerce_wp_checkbox(array(
Loading history...
133
            'id'      => 'pagantis_promoted',
134
            '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

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

152
        /** @scrutinizer ignore-call */ 
153
        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

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

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

163
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . /** @scrutinizer ignore-call */ get_locale() . '.mo';
Loading history...
Bug introduced by
The constant WP_LANG_DIR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
164
        }
165
166
        return $mofile;
167
    }
168
169
    /**
170
     * Sql table
171
     */
172
    public function pagantisActivation()
173
    {
174
        global $wpdb;
175
176
        $tableName = $wpdb->prefix . self::CONCURRENCY_TABLE;
177
        if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName) {
178
            $charset_collate = $wpdb->get_charset_collate();
179
            $sql             = "CREATE TABLE $tableName ( order_id int NOT NULL,  
180
                    createdAt timestamp DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY id (order_id)) $charset_collate";
181
            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...
182
            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

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

291
        $settings = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
292
293
        if ( ! isset($settings['pagantis_public_key']) && $settings['public_key']) {
294
            $settings['pagantis_public_key'] = $settings['public_key'];
295
            unset($settings['public_key']);
296
        }
297
298
        if ( ! isset($settings['pagantis_private_key']) && $settings['secret_key']) {
299
            $settings['pagantis_private_key'] = $settings['secret_key'];
300
            unset($settings['secret_key']);
301
        }
302
303
        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

303
        /** @scrutinizer ignore-call */ 
304
        update_option('woocommerce_pagantis_settings', $settings);
Loading history...
304
    }
305
306
    /**
307
     * Product simulator
308
     */
309
    public function pagantisAddProductSimulator()
310
    {
311
        global $product;
312
313
        $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

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

314
        $locale           = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
315
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
316
        $allowedCountry   = (in_array(strtolower($locale), $allowedCountries));
317
        $minAmount        = $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'];
318
        $maxAmount        = $this->extraConfig['PAGANTIS_DISPLAY_MAX_AMOUNT'];
319
        $totalPrice       = $product->get_price();
320
        $validAmount      = ($totalPrice >= $minAmount && ($totalPrice <= $maxAmount || $maxAmount == '0'));
321
        if ($cfg['enabled'] !== 'yes' || $cfg['pagantis_public_key'] == '' || $cfg['pagantis_private_key'] == ''
322
            || $cfg['simulator'] !== 'yes'
323
            || ! $allowedCountry
324
            || ! $validAmount
325
        ) {
326
            return;
327
        }
328
329
        $post_id         = $product->get_id();
330
        $template_fields = array(
331
            'total'                     => is_numeric($product->get_price()) ? $product->get_price() : 0,
332
            'public_key'                => $cfg['pagantis_public_key'],
333
            'simulator_type'            => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE'],
334
            'positionSelector'          => $this->extraConfig['PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'],
335
            'quantitySelector'          => unserialize($this->extraConfig['PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR']),
336
            'priceSelector'             => unserialize($this->extraConfig['PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR']),
337
            'totalAmount'               => is_numeric($product->get_price()) ? $product->get_price() : 0,
338
            'locale'                    => $locale,
339
            'country'                   => $locale,
340
            'promoted'                  => $this->isPromoted($post_id),
341
            'promotedMessage'           => $this->extraConfig['PAGANTIS_PROMOTION_EXTRA'],
342
            'thousandSeparator'         => $this->extraConfig['PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'],
343
            'decimalSeparator'          => $this->extraConfig['PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR'],
344
            'pagantisQuotesStart'       => $this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS'],
345
            'pagantisSimulatorSkin'     => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_SKIN'],
346
            'pagantisSimulatorPosition' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION'],
347
            'finalDestination'          => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_SITUATION'],
348
            'variationSelector'         => $this->extraConfig['PAGANTIS_SIMULATOR_SELECTOR_VARIATION'],
349
            'productType'               => $product->get_type()
350
        );
351
352
        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

352
        /** @scrutinizer ignore-call */ 
353
        wc_get_template('product_simulator.php', $template_fields, '', $this->template_path);
Loading history...
353
    }
354
355
    /**
356
     * Add Pagantis to payments list.
357
     *
358
     * @param $methods
359
     *
360
     * @return array
361
     */
362
    public function addPagantisGateway($methods)
363
    {
364
        if ( ! class_exists('WC_Payment_Gateway')) {
365
            return $methods;
366
        }
367
368
        include_once('controllers/paymentController.php');
369
        $methods[] = 'WcPagantisGateway';
370
371
        return $methods;
372
    }
373
374
    /**
375
     * Initialize WC_Pagantis class
376
     *
377
     * @param $methods
378
     *
379
     * @return mixed
380
     */
381
    public function pagantisFilterGateways($methods)
382
    {
383
        $pagantis = new WcPagantisGateway();
384
        if ( ! $pagantis->is_available()) {
385
            unset($methods['pagantis']);
386
        }
387
388
        return $methods;
389
    }
390
391
    /**
392
     * Add links to Plugin description
393
     *
394
     * @param $links
395
     *
396
     * @return mixed
397
     */
398
    public function pagantisActionLinks($links)
399
    {
400
        $params_array = array('page' => 'wc-settings', 'tab' => 'checkout', 'section' => 'pagantis');
401
        $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

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

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

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

402
        $setting_link = '<a href="' . $setting_url . '">' . /** @scrutinizer ignore-call */ __('Settings', 'pagantis') . '</a>';
Loading history...
403
404
        array_unshift($links, $setting_link);
405
406
        return $links;
407
    }
408
409
    /**
410
     * Add links to Plugin options
411
     *
412
     * @param $links
413
     * @param $file
414
     *
415
     * @return array
416
     */
417
    public function pagantisRowMeta($links, $file)
418
    {
419
        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

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

420
            $links[] = '<a href="' . WcPagantis::GIT_HUB_URL . '" target="_blank">' . /** @scrutinizer ignore-call */ __('Documentation', 'pagantis') . '</a>';
Loading history...
421
            $links[] = '<a href="' . WcPagantis::PAGANTIS_DOC_URL . '" target="_blank">' . __('API documentation', 'pagantis') . '</a>';
422
            $links[] = '<a href="' . WcPagantis::SUPPORT_EML . '">' . __('Support', 'pagantis') . '</a>';
423
424
            return $links;
425
        }
426
427
        return $links;
428
    }
429
430
    /**
431
     * Read logs
432
     */
433
    public function readLogs($data)
434
    {
435
        global $wpdb;
436
        $filters    = ($data->get_params());
437
        $response   = array();
438
        $secretKey  = $filters['secret'];
439
        $from       = $filters['from'];
440
        $to         = $filters['to'];
441
        $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

441
        $cfg        = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
442
        $privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
443
        $tableName  = $wpdb->prefix . self::LOGS_TABLE;
444
        $query      = "select * from $tableName where createdAt>$from and createdAt<$to order by createdAt desc";
445
        $results    = $wpdb->get_results($query);
446
        if (isset($results) && $privateKey == $secretKey) {
447
            foreach ($results as $key => $result) {
448
                $response[$key]['timestamp'] = $result->createdAt;
449
                $response[$key]['log']       = json_decode($result->log);
450
            }
451
        } else {
452
            $response['result'] = 'Error';
453
        }
454
        $response = json_encode($response);
455
        header("HTTP/1.1 200", true, 200);
456
        header('Content-Type: application/json', true);
457
        header('Content-Length: ' . strlen($response));
458
        echo($response);
459
        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...
460
    }
461
462
    /**
463
     * Update extra config
464
     */
465
    public function updateExtraConfig($data)
466
    {
467
        global $wpdb;
468
        $tableName = $wpdb->prefix . self::CONFIG_TABLE;
469
        $response  = array('status' => null);
470
471
        $filters    = ($data->get_params());
472
        $secretKey  = $filters['secret'];
473
        $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

473
        $cfg        = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
474
        $privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
475
        if ($privateKey != $secretKey) {
476
            $response['status'] = 401;
477
            $response['result'] = 'Unauthorized';
478
        } elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
479
            if (count($_POST)) {
480
                foreach ($_POST as $config => $value) {
481
                    if (isset($this->defaultConfigs[$config]) && $response['status'] == null) {
482
                        $wpdb->update($tableName, array('value' => stripslashes($value)), array('config' => $config), array('%s'), array('%s'));
483
                    } else {
484
                        $response['status'] = 400;
485
                        $response['result'] = 'Bad request';
486
                    }
487
                }
488
            } else {
489
                $response['status'] = 422;
490
                $response['result'] = 'Empty data';
491
            }
492
        }
493
494
        if ($response['status'] == null) {
495
            $tableName = $wpdb->prefix . self::CONFIG_TABLE;
496
            $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...
497
            foreach ($dbResult as $value) {
498
                $formattedResult[$value['config']] = $value['value'];
499
            }
500
            $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 497. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
501
        }
502
503
        $result = json_encode($response['result']);
504
        header("HTTP/1.1 " . $response['status'], true, $response['status']);
505
        header('Content-Type: application/json', true);
506
        header('Content-Length: ' . strlen($result));
507
        echo($result);
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
     * Read logs
513
     */
514
    public function readApi($data)
515
    {
516
        global $wpdb;
517
        $filters        = ($data->get_params());
518
        $response       = array('timestamp' => time());
519
        $secretKey      = $filters['secret'];
520
        $from           = ($filters['from']) ? date_create($filters['from']) : date("Y-m-d", strtotime("-7 day"));
521
        $to             = ($filters['to']) ? date_create($filters['to']) : date("Y-m-d", strtotime("+1 day"));
522
        $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...
523
        $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

523
        $cfg            = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
524
        $privateKey     = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
525
        $tableName      = $wpdb->prefix . self::ORDERS_TABLE;
526
        $tableNameInner = $wpdb->prefix . 'postmeta';
527
        $query          = "select * from $tableName tn INNER JOIN $tableNameInner tn2 ON tn2.post_id = tn.id
528
                  where tn.post_type='shop_order' and tn.post_date>'" . $from->format("Y-m-d") . "' 
529
                  and tn.post_date<'" . $to->format("Y-m-d") . "' order by tn.post_date desc";
530
        $results        = $wpdb->get_results($query);
531
532
        if (isset($results) && $privateKey == $secretKey) {
533
            foreach ($results as $result) {
534
                $key                                          = $result->ID;
535
                $response['message'][$key]['timestamp']       = $result->post_date;
536
                $response['message'][$key]['order_id']        = $key;
537
                $response['message'][$key][$result->meta_key] = $result->meta_value;
538
            }
539
        } else {
540
            $response['result'] = 'Error';
541
        }
542
        $response = json_encode($response);
543
        header("HTTP/1.1 200", true, 200);
544
        header('Content-Type: application/json', true);
545
        header('Content-Length: ' . strlen($response));
546
        echo($response);
547
        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...
548
    }
549
550
    /**
551
     * ENDPOINT - Read logs -> Hook: rest_api_init
552
     *
553
     * @return mixed
554
     */
555
    public function pagantisRegisterEndpoint()
556
    {
557
        register_rest_route('pagantis/v1', '/logs/(?P<secret>\w+)/(?P<from>\d+)/(?P<to>\d+)', array(
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

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

637
        $metaProduct = /** @scrutinizer ignore-call */ get_post_meta($product_id);
Loading history...
638
639
        return (array_key_exists('custom_product_pagantis_promoted', $metaProduct)
640
                && $metaProduct['custom_product_pagantis_promoted']['0'] === 'yes') ? 'true' : 'false';
641
    }
642
643
    /**
644
     * Dump variable.
645
     */
646
647
    function d()
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
648
    {
649
        call_user_func_array('dump', func_get_args());
650
    }
651
652
653
    /**
654
     * Dump variables and die.
655
     */
656
657
    function dd()
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
658
    {
659
        call_user_func_array('dump', func_get_args());
660
        die();
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...
661
    }
662
663
}
664
665
/**
666
 * Add widget Js
667
 **/
668
function add_pagantis_widget_js()
669
{
670
    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

670
    /** @scrutinizer ignore-call */ 
671
    wp_enqueue_script('pgSDK', 'https://cdn.pagantis.com/js/pg-v2/sdk.js', '', '', true);
Loading history...
671
}
672
673
$WcPagantis = new WcPagantis();
674