Completed
Push — master ( e00620...73f050 )
by
unknown
16s queued 11s
created

WcPagantis::pagantisPromotedVarSave()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

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

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

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

112
        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

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

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

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

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

143
        /** @scrutinizer ignore-call */ 
144
        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

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

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

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

244
        $settings = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
245
246
        if (!isset($settings['pagantis_public_key']) && $settings['public_key']) {
247
            $settings['pagantis_public_key'] = $settings['public_key'];
248
            unset($settings['public_key']);
249
        }
250
251
        if (!isset($settings['pagantis_private_key']) && $settings['secret_key']) {
252
            $settings['pagantis_private_key'] = $settings['secret_key'];
253
            unset($settings['secret_key']);
254
        }
255
256
        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

256
        /** @scrutinizer ignore-call */ 
257
        update_option('woocommerce_pagantis_settings', $settings);
Loading history...
257
    }
258
259
    /**
260
     * Product simulator
261
     */
262
    public function pagantisAddProductSimulator()
263
    {
264
        global $product;
265
266
        $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

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

267
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
268
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
269
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
270
        if ($cfg['enabled'] !== 'yes' || $cfg['pagantis_public_key'] == '' || $cfg['pagantis_private_key'] == '' ||
271
            $cfg['simulator'] !== 'yes' ||  $product->price < $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'] ||
272
            !$allowedCountry ) {
273
            return;
274
        }
275
276
        $post_id = $product->get_id();
277
        $template_fields = array(
278
            'total'    => is_numeric($product->price) ? $product->price : 0,
279
            'public_key' => $cfg['pagantis_public_key'],
280
            'simulator_type' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE'],
281
            'positionSelector' => $this->extraConfig['PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'],
282
            'quantitySelector' => unserialize($this->extraConfig['PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR']),
283
            'priceSelector' => unserialize($this->extraConfig['PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR']),
284
            'totalAmount' => is_numeric($product->price) ? $product->price : 0,
285
            'locale' => $locale,
286
            'promoted' => $this->isPromoted($post_id),
287
            'promotedMessage' => $this->extraConfig['PAGANTIS_PROMOTION_EXTRA']
288
        );
289
        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

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

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

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

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

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

339
        $setting_link = '<a href="'.$setting_url.'">'./** @scrutinizer ignore-call */ __('Settings', 'pagantis').'</a>';
Loading history...
340
341
        array_unshift($links, $setting_link);
342
343
        return $links;
344
    }
345
346
    /**
347
     * Add links to Plugin options
348
     *
349
     * @param $links
350
     * @param $file
351
     *
352
     * @return array
353
     */
354
    public function pagantisRowMeta($links, $file)
355
    {
356
        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

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

357
            $links[] = '<a href="'.WcPagantis::GIT_HUB_URL.'" target="_blank">'./** @scrutinizer ignore-call */ __('Documentation', 'pagantis').'</a>';
Loading history...
358
            $links[] = '<a href="'.WcPagantis::PAGANTIS_DOC_URL.'" target="_blank">'.
359
                       __('API documentation', 'pagantis').'</a>';
360
            $links[] = '<a href="'.WcPagantis::SUPPORT_EML.'">'.__('Support', 'pagantis').'</a>';
361
362
            return $links;
363
        }
364
365
        return $links;
366
    }
367
368
    /**
369
     * Read logs
370
     */
371
    public function readLogs($data)
372
    {
373
        global $wpdb;
374
        $filters   = ($data->get_params());
375
        $response  = array();
376
        $secretKey = $filters['secret'];
377
        $from = $filters['from'];
378
        $to   = $filters['to'];
379
        $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

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

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

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

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

592
        $metaProduct = /** @scrutinizer ignore-call */ get_post_meta($product_id);
Loading history...
593
        return ($metaProduct['custom_product_pagantis_promoted']['0'] === 'yes') ? 'true' : 'false';
594
    }
595
}
596
597
/**
598
 * Add widget Js
599
 **/
600
function add_pagantis_widget_js()
601
{
602
    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

602
    /** @scrutinizer ignore-call */ 
603
    wp_enqueue_script('pgSDK', 'https://cdn.pagantis.com/js/pg-v2/sdk.js', '', '', true);
Loading history...
603
    wp_enqueue_script('pmtSDK', 'https://cdn.pagamastarde.com/js/pmt-v2/sdk.js', '', '', true);
604
}
605
606
$WcPagantis = new WcPagantis();
607