wps_orders_ctr::__construct()   B
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 26
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 10
nc 1
nop 0
dl 0
loc 26
rs 8.8571
c 0
b 0
f 0
1
<?php if ( ! defined( 'ABSPATH' ) ) { exit;
2
}
3
class wps_orders_ctr {
4
5
	/** Define the main directory containing the template for the current plugin
6
	 *
7
	 * @var string
8
	 */
9
	private $template_dir;
10
	/**
11
	 * Define the directory name for the module in order to check into frontend
12
	 *
13
	 * @var string
14
	 */
15
	private $plugin_dirname = WPS_ORDERS_DIR;
0 ignored issues
show
Unused Code introduced by
The property $plugin_dirname is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
16
	function __construct() {
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...
17
18
		/** Template Load */
19
		$this->template_dir = WPS_ORDERS_PATH . WPS_ORDERS_DIR . '/templates/';
20
21
		/** Template Load */
22
		// add_filter( 'wpshop_custom_template', array( &$this, 'custom_template_load' ) );
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
23
		add_shortcode( 'order_customer_informations', array( &$this, 'display_order_customer_informations' ) );
24
		add_shortcode( 'wps_orders_in_customer_account', array( $this, 'shortcode_callback_display_orders_in_account' ) );
25
		add_action( 'wp_enqueue_scripts', array( $this, 'wps_orders_scripts' ) );
26
		/**	Include the different javascript	*/
27
		add_action( 'admin_init', array( &$this, 'admin_js' ) );
28
29
		/** Ajax Actions */
30
		// add_action( 'wp_ajax_wps_add_product_to_quotation', array( &$this, 'wps_add_product_to_quotation') );
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
31
		// add_action( 'wap_ajax_wps_change_product_list', array( &$this, 'wps_change_product_list') );
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
32
		// add_action( 'wap_ajax_wps_orders_load_variations_container', array( &$this, 'wps_orders_load_variations_container') );
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
33
		// add_action( 'wap_ajax_wps_order_refresh_in_admin', array( &$this, 'wps_order_refresh_in_admin') );
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
34
		add_action( 'wp_ajax_wps_orders_load_details', array( $this, 'wps_orders_load_details' ) );
35
		// Add a product sale historic in administration product panel
36
		add_action( 'wp_ajax_wps_order_choose_customer', array( $this, 'wps_order_choose_customer' ) );
37
		/** For delete order */
38
		add_action( 'wp_ajax_wps_delete_order', array( $this, 'wps_delete_order' ) );
39
		/** Invoice Page */
40
		add_action( 'admin_post_wps_invoice', array( $this, 'wps_invoice_output' ) );
41
	}
42
43
		/**
44
		 * Include stylesheets
45
		 */
46
	function admin_js() {
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...
47
48
		add_thickbox();
49
	}
50
51
52
	/**
53
	 * Add scripts
54
	 */
55
	function wps_orders_scripts() {
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...
56
57
		wp_enqueue_script( 'wps_orders_fronend', WPS_ORDERS_URL . WPS_ORDERS_DIR . '/assets/frontend/js/wps_orders.js' );
58
	}
59
60
	function display_order_customer_informations() {
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...
61
62
		global $post_id;
63
		global $wpdb;
64
		$output = '';
65
		if ( ! empty( $post_id ) ) {
66
			$order_postmeta = get_post_meta( $post_id, '_order_postmeta', true );
67
			$order_info = get_post_meta( $post_id, '_order_info', true );
68
			/** Check the order status */
69
			if ( ! empty( $order_postmeta ) ) {
70
				if ( ! empty( $order_postmeta['order_status'] )  && $order_postmeta['order_status'] != 'awaiting_payment' ) {
71
					$output = wps_address::display_an_address( $order_info['billing']['address'] );
72
					$output .= wps_address::display_an_address( $order_info['shipping']['address'] );
73
				} else {
74
					$output = wps_address::display_an_address( $order_info['billing']['address'] );
75
				}
76
			}
77
		} else {
78
			/** Display  "Choose customer or create one" Interface */
79
			$tpl_component = array();
80
			$args = array(
81
			'show_option_all' => __( 'Choose a customer', 'wpshop' ),
82
			'orderby' => 'display_name',
83
			'order' => 'ASC',
84
			'include' => null, // string
85
						'exclude' => null, // string
86
						'multi' => false,
87
			'show' => 'display_name',
88
			'echo' => false,
89
			'selected' => false,
90
			'include_selected' => false,
91
			'name' => 'user', // string
92
						'id' => null, // integer
93
						'class' => 'chosen_select', // string
94
						'blog_id' => $GLOBALS['blog_id'],
95
			'who' => null,// string
96
			);
97
			$tpl_component['CUSTOMERS_LIST'] = wp_dropdown_users( $args );
98
			$output = wpshop_display::display_template_element( 'wps_orders_choose_customer_interface', $tpl_component, array(), 'admin' );
99
		}
100
		return $output;
101
	}
102
103
	/**
104
	 * Affichage du shortcode générant la liste des commandes d'un client
105
	 *
106
	 * @version 1.4.4.3
107
	 *
108
	 * @param  array $args Les arguments passés au shortcode.
109
	 */
110
	function shortcode_callback_display_orders_in_account( $args ) {
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...
111
		$customer_id = ! empty( $args ) && ! empty( $args['cid'] ) ? (int) $args['cid'] : wps_customer_ctr::get_customer_id_by_author_id( get_current_user_id() );
112
		return $this->display_orders_in_account( $customer_id );
113
	}
114
115
	/**
116
	 * Display orders in customer account
117
	 *
118
	 * @param integer $customer_id Identifiant du client pour qui afficher les commandes / The customer identifier we want to have order list for.
119
	 *
120
	 * @return string
121
	 */
122
	function display_orders_in_account( $customer_id = '' ) {
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...
123
		$output = '';
0 ignored issues
show
Unused Code introduced by
$output is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
124
		$customer_id = ( ! empty( $customer_id ) ) ? $customer_id : wps_customer_ctr::get_customer_id_by_author_id( get_current_user_id() );
125
		$wps_orders_mdl = new wps_orders_mdl();
126
		$orders = $wps_orders_mdl->get_customer_orders( $customer_id );
0 ignored issues
show
Unused Code introduced by
$orders is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
127
128
		$shipping_address_option = get_option( 'wpshop_shipping_address_choice' );
129
		// Vérification de l'activation ou non des livraisons pour l'affichage des adresses correspondantes / Check shipping addresses state in order to display or not addresses.
130
		$shipping_addresses_activated = ( ! empty( $shipping_address_option ) && ! empty( $shipping_address_option['activate'] ) ) ? true : false;
0 ignored issues
show
Unused Code introduced by
$shipping_addresses_activated is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
131
132
		ob_start();
133
		require_once( wpshop_tools::get_template_part( WPS_ORDERS_DIR, $this->template_dir, 'frontend', 'orders_list_in_account' ) );
134
		$output = ob_get_contents();
135
		ob_end_clean();
136
137
		return $output;
138
	}
139
140
		/**
141
		 *	Build an array with the different items to add to an order
142
		 *
143
		 *	@param array $products The item list to add to the order
0 ignored issues
show
Documentation introduced by
There is no parameter named $products. Did you maybe mean $product?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
144
		 *
145
		 *	@return array $item_list The item to add to order
146
		 */
147
	function add_product_to_order( $product ) {
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...
148
149
		global $wpdb;
150
		if ( ! empty( $product ) && empty( $product['price_ttc_before_discount'] ) && empty( $product['price_ht_before_discount'] ) ) {
151
			$price_infos = wpshop_prices::check_product_price( $product, true );
152
			$product['price_ht'] = ( ! empty( $price_infos['discount'] ) && ! empty( $price_infos['discount']['discount_exist'] ) && $price_infos['discount']['discount_exist']) ?  $price_infos['discount']['discount_et_price'] : $price_infos['et'];
153
			$product['product_price'] = ( ! empty( $price_infos['discount'] ) && ! empty( $price_infos['discount']['discount_exist'] ) && $price_infos['discount']['discount_exist']) ? $price_infos['discount']['discount_ati_price'] : $price_infos['ati'];
154
			$product['tva'] = ( ! empty( $price_infos['discount'] ) && ! empty( $price_infos['discount']['discount_exist'] ) && $price_infos['discount']['discount_exist']) ? $price_infos['discount']['discount_tva'] : $price_infos['tva'];
155
		}
156
157
		$price_piloting = get_option( 'wpshop_shop_price_piloting' );
158
		if ( ! empty( $price_piloting ) && $price_piloting == 'HT' ) {
159
			$total_ht = $product['price_ht'] * $product['product_qty'];
160
			$tva_total_amount = $total_ht * ( $product['tx_tva'] / 100 );
161
			$total_ttc = $total_ht + $tva_total_amount;
162
		} else {
163
			$total_ttc = $product['product_price'] * $product['product_qty'];
164
			$total_ht  = $total_ttc / ( 1 + ( $product['tx_tva'] / 100 ) );
165
			$tva_total_amount = $total_ttc - $total_ht;
166
		}
167
168
		$tva = ! empty( $product[ WPSHOP_PRODUCT_PRICE_TAX ] ) ? $product[ WPSHOP_PRODUCT_PRICE_TAX ] : null;
169
		$item_discount_type = $item_discount_value = $item_discount_amount = 0;
170
		$d_amount = ! empty( $product ) && ! empty( $product['discount_amount'] ) ? wpshop_tools::formate_number( $product['discount_amount'] ) : null;
0 ignored issues
show
Documentation introduced by
$product['discount_amount'] is of type integer|double, but the function expects a object<unknown_type>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
171
		$d_rate = ! empty( $product ) && ! empty( $product['discount_rate'] ) ? wpshop_tools::formate_number( $product['discount_rate'] ) : null;
0 ignored issues
show
Documentation introduced by
$product['discount_rate'] is of type integer|double, but the function expects a object<unknown_type>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
172
		$d_special = ! empty( $product ) && ! empty( $product['special_price'] ) ? wpshop_tools::formate_number( $product['special_price'] ) : null;
0 ignored issues
show
Documentation introduced by
$product['special_price'] is of type integer|double, but the function expects a object<unknown_type>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
173
		if ( ! empty( $d_amount ) ) {
174
			$item_discount_type = 'discount_amount';
175
			$item_discount_amount = $product['discount_amount'];
176
			$item_discount_value = $product['discount_amount'];
177
		} elseif ( ! empty( $d_rate ) ) {
178
			$item_discount_type = 'discount_rate';
179
			$item_discount_amount = $product['discount_rate'];
180
			$item_discount_value = $product['discount_rate'];
181
		} elseif ( ! empty( $d_special ) ) {
182
			$item_discount_type = 'special_price';
183
			$item_discount_amount = $product['special_price'];
184
			$item_discount_value = $product['special_price'];
185
		}
186
187
		$item = array(
188
			'item_id' => $product['product_id'],
189
			'item_ref' => ! empty( $product['product_reference'] ) ? $product['product_reference'] : null,
190
			'item_name' => ! empty( $product['product_name'] ) ? $product['product_name'] : 'wpshop_product_' . $product['product_id'],
191
			'item_qty' => $product['product_qty'],
192
			'item_pu_ht' => $product['price_ht'],
193
			'item_pu_ttc' => $product['product_price'],
194
			'item_ecotaxe_ht' => 0,
195
			'item_ecotaxe_tva' => 19.6,
196
			'item_ecotaxe_ttc' => 0,
197
			'item_discount_type' => $item_discount_type,
198
			'item_discount_value' => $item_discount_value,
199
			'item_discount_amount' => $item_discount_amount,
200
			'item_tva_rate' => $tva,
201
			'item_tva_amount' => $product['tva'],
202
			'item_total_ht' => $total_ht,
203
			'item_tva_total_amount' => $tva_total_amount,
204
			'item_total_ttc' => $total_ttc,
205
			'item_meta' => ! empty( $product['item_meta'] ) ? $product['item_meta'] : array(),
206
		);
207
		if ( isset( $product['is_downloadable_'] ) ) {
208
			$item['item_is_downloadable_'] = $product['is_downloadable_'];
209
		}
210
		$array_not_to_do = array( WPSHOP_PRODUCT_PRICE_HT, WPSHOP_PRODUCT_PRICE_TTC, WPSHOP_PRODUCT_PRICE_TAX_AMOUNT, 'product_qty', WPSHOP_PRODUCT_PRICE_TAX, 'product_id', 'product_reference', 'product_name', 'variations' );
211
		if ( ! empty( $product['item_meta'] ) ) {
212
			foreach ( $product['item_meta'] as $key => $value ) {
0 ignored issues
show
Bug introduced by
The expression $product['item_meta'] of type integer|double is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
213
				if ( ! isset( $item[ 'item_' . $key ] ) && ! in_array( $key, $array_not_to_do ) && ! empty( $product[ $key ] ) ) {
214
					$item[ 'item_' . $key ] = $product[ $key ];
215
				}
216
			}
217
		}
218
219
		/** Check if it's a variation product */
220
		if ( ! empty( $product ) && ! empty( $product['item_meta'] ) && ! empty( $product['item_meta']['variations'] ) ) {
221
			foreach ( $product['item_meta']['variations'] as $k => $variation ) {
222
				$product_variation_def = get_post_meta( $k, '_wpshop_variations_attribute_def', true );
223 View Code Duplication
				if ( ! empty( $product_variation_def ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
224
					foreach ( $product_variation_def as $attribute_code => $variation_id ) {
225
						$variation_attribute_def = wpshop_attributes::getElement( $attribute_code, '"valid"', 'code' );
226
						if ( ! empty( $variation_attribute_def ) ) {
227
							$item['item_meta']['variation_definition'][ $attribute_code ]['NAME'] = $variation_attribute_def->frontend_label;
228
							if ( $variation_attribute_def->data_type_to_use == 'custom' ) {
229
								$query = $wpdb->prepare( 'SELECT label FROM ' . WPSHOP_DBT_ATTRIBUTE_VALUES_OPTIONS . ' WHERE id=%d', $variation_id );
230
								$variation_name = $wpdb->get_var( $query );
231
							} else {
232
								$variation_post = get_post( $variation_id );
233
								$variation_name = $variation_post->post_title;
234
							}
235
							$item['item_meta']['variation_definition'][ $attribute_code ]['UNSTYLED_VALUE'] = $variation_name;
236
							$item['item_meta']['variation_definition'][ $attribute_code ]['VALUE'] = $variation_name;
237
						}
238
					}
239
				}
240
			}
241
		} else {
242
				/** Check if it's product with one variation */
243
				$product_variation_def = get_post_meta( $product['product_id'], '_wpshop_variations_attribute_def', true );
244 View Code Duplication
			if ( ! empty( $product_variation_def ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
245
				foreach ( $product_variation_def as $attribute_code => $variation_id ) {
246
					$variation_attribute_def = wpshop_attributes::getElement( $attribute_code, '"valid"', 'code' );
247
					if ( ! empty( $variation_attribute_def ) ) {
248
							$item['item_meta']['variation_definition'][ $attribute_code ]['NAME'] = $variation_attribute_def->frontend_label;
249
						if ( $variation_attribute_def->data_type_to_use == 'custom' ) {
250
								$query = $wpdb->prepare( 'SELECT label FROM ' . WPSHOP_DBT_ATTRIBUTE_VALUES_OPTIONS . ' WHERE id=%d', $variation_id );
251
							$variation_name = $wpdb->get_var( $query );
252
						} else {
253
							$variation_post = get_post( $variation_id );
254
							$variation_name = $variation_post->post_title;
255
						}
256
						$item['item_meta']['variation_definition'][ $attribute_code ]['UNSTYLED_VALUE'] = $variation_name;
257
						$item['item_meta']['variation_definition'][ $attribute_code ]['VALUE'] = $variation_name;
258
					}
259
				}
260
			}
261
		}
262
263
		/**	On ajoute la possibilité d'étendre les données produits ajoutées dans le panier / Add possibility to extends product data saved into cart	*/
264
		$item = apply_filters( 'wpshop-add-product-to-order', $item, $product );
265
		return $item;
266
	}
267
268
		/**
269
		 *	Output invoice
270
		 */
271
	function wps_invoice_output() {
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...
272
273
		$order_id = ( ! empty( $_GET['order_id'] )) ? (int) $_GET['order_id'] : null;
274
		$invoice_ref = ( ! empty( $_GET['invoice_ref'] )) ? sanitize_text_field( $_GET['invoice_ref'] ) : null;
275
		$mode = ( ! empty( $_GET['mode'] )) ? sanitize_text_field( $_GET['mode'] ) : 'html';
276
		$is_credit_slip = ( ! empty( $_GET['credit_slip'] )) ? sanitize_text_field( $_GET['credit_slip'] ) : null;
277
		$user_id = get_current_user_id();
278
		if ( ! empty( $order_id ) && $user_id != 0 ) {
279
			/**	Order reading	*/
280
			$order_postmeta = get_post_meta( $order_id, '_order_postmeta', true );
281
			/**	Start invoice display	*/
282
			if ( ! empty( $is_credit_slip ) ) {
283
				$html_content = wpshop_modules_billing::generate_html_invoice( $order_id, $invoice_ref, 'credit_slip' );
284
			} else {
285
				$html_content = wpshop_modules_billing::generate_html_invoice( $order_id, $invoice_ref );
286
			}
287
288
			/**
289
			 * Génération de la facture au format PDF
290
			 */
291
			if ( 'pdf' === $mode ) {
292
				require_once( WPSHOP_LIBRAIRIES_DIR . 'HTML2PDF/html2pdf.class.php' );
293
				try {
294
					// $html_content = wpshop_display::display_template_element('invoice_print_page_content_css', array(), array(), 'common') . '<page>' . $html_content . '</page>';
0 ignored issues
show
Unused Code Comprehensibility introduced by
52% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
295
					$html_content = wpshop_display::display_template_element( 'invoice_page_content_css', array(), array(), 'common' ) . '<page>' . $html_content . '</page>';
296
					$html2pdf = new HTML2PDF( 'P', 'A4', 'fr' );
297
					$html2pdf->setDefaultFont( 'Arial' );
298
					$html2pdf->writeHTML( $html_content );
299
					ob_clean();
300
					$html2pdf->Output( apply_filters( 'wps_filter_invoice_filename', 'order_' . $order_id . '.pdf', $order_id ), 'D' );
301
				} catch (HTML2PDF_exception $e) {
302
					echo $e;
303
					exit;
304
				}
305
			} else {
306
				$order_invoice_ref = ( ! empty( $order_postmeta['order_invoice_ref'] ) ) ? $order_postmeta['order_invoice_ref'] : '';
307
				$tpl_component['INVOICE_CSS'] = wpshop_display::display_template_element( 'invoice_page_content_css', array(), array(), 'common' );
0 ignored issues
show
Coding Style Comprehensibility introduced by
$tpl_component was never initialized. Although not strictly required by PHP, it is generally a good practice to add $tpl_component = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
308
				$tpl_component['INVOICE_MAIN_PAGE'] = $html_content;
309
				$tpl_component['INVOICE_TITLE_PAGE'] = sprintf( __( 'Invoice %1$s for order %3$s (#%2$s)', 'wpshop' ), $order_invoice_ref, $order_id, $order_postmeta['order_key'] );
310
				echo wpshop_display::display_template_element( 'invoice_page', $tpl_component, array(), 'common' );
311
			}
312
		}
313
		die();
314
	}
315
316
317
		/**
318
		 * AJAX - Load order details in customer account
319
		 */
320
	function wps_orders_load_details() {
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...
321
322
		check_ajax_referer( 'wps_orders_load_details' );
323
		$order_id = ( ! empty( $_POST['order_id'] ) ) ? wpshop_tools::varSanitizer( $_POST['order_id'] ) : '';
324
		$user_id = get_current_user_id();
325
		$status = false;
326
		$result = '';
327
		if ( ! empty( $order_id ) ) {
328
			$order = get_post( $order_id );
329
			$order_infos = get_post_meta( $order_id, '_order_postmeta', true );
330
			$order_key = ( ! empty( $order_infos['order_key'] ) ) ? $order_infos['order_key'] : '-';
331
			if ( ! empty( $order ) && ! empty( $user_id ) && $order->post_type == WPSHOP_NEWTYPE_IDENTIFIER_ORDER && $order->post_author == $user_id ) {
332
				$result = do_shortcode( '[wps_cart cart_type="summary" oid="' . $order_id . '"]' );
333
				$status = true;
334
			}
335
		}
336
		echo json_encode( array( 'status' => $status, 'title' => sprintf( __( 'Order n° %s details', 'wpshop' ), $order_key ), 'content' => $result ) );
0 ignored issues
show
Bug introduced by
The variable $order_key does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
337
		wp_die();
338
	}
339
340
		/**
341
		 * AJAX - Choose customer to create order
342
		 */
343
	function wps_order_choose_customer() {
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...
344
345
		$_wpnonce = ! empty( $_REQUEST['_wpnonce'] ) ? sanitize_text_field( $_REQUEST['_wpnonce'] ) : '';
346
		if ( ! wp_verify_nonce( $_wpnonce, 'wps_order_choose_customer' ) ) {
347
				wp_die();
348
		}
349
350
		$status = false;
351
		$billing_data = $shipping_data = '';
352
		$customer_id = ( ! empty( $_POST['customer_id'] ) ) ? intval( $_POST['customer_id'] ): null;
353
		if ( ! empty( $customer_id ) ) {
354
			$wps_address = new wps_address();
355
			$billing_option = get_option( 'wpshop_billing_address' );
356
			$shipping_option = get_option( 'wpshop_shipping_address_choice' );
357
			$billing_option = $billing_option['choice'];
358
			$customer_addresses_list = wps_address::get_addresses_list( $customer_id );
359
			$status = true;
360
			$billing_data = '<div class="wps-alert-info">' . sprintf( __( 'No Billing address created, <a href="%s" title="' . __( 'Create a new billing address', 'wpshop' ) . '" class="thickbox">create one</a>', 'wpshop' ),admin_url( 'admin-ajax.php' ) . '?action=wps-add-an-address-in-admin&address_type=' . $billing_option . '&customer_id=' . $customer_id . '&height=600' ) . '</div>';
361
			if ( ! empty( $shipping_option ) && ! empty( $shipping_option['activate'] ) ) {
362
				$shipping_option = $shipping_option['choice'];
363
				$shipping_data = '<div class="wps-alert-info">' . sprintf( __( 'No shipping address created, <a href="%s" title="' . __( 'Create a new shipping address', 'wpshop' ) . '" class="thickbox">create one</a>', 'wpshop' ),admin_url( 'admin-ajax.php' ) . '?action=wps-add-an-address-in-admin&address_type=' . $shipping_option . '&customer_id=' . $customer_id . '&height=600' ) . '</div>';
364
			}
365
366
			if ( ! empty( $customer_addresses_list ) ) {
367
				foreach ( $customer_addresses_list as $address_type => $customer_addresses ) {
368
					if ( $billing_option == $address_type ) {
369
						$billing_data = $wps_address->display_address_in_administration( $customer_addresses, $address_type );
0 ignored issues
show
Bug introduced by
The method display_address_in_administration() does not exist on wps_address. Did you maybe mean display_address()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
370
					} else {
371
						$shipping_data = $wps_address->display_address_in_administration( $customer_addresses, $address_type );
0 ignored issues
show
Bug introduced by
The method display_address_in_administration() does not exist on wps_address. Did you maybe mean display_address()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
372
					}
373
				}
374
			}
375
		}
376
		echo json_encode( array( 'status' => $status, 'billing_data' => $billing_data, 'shipping_data' => $shipping_data ) );
377
		wp_die();
378
	}
379
380
	static function pay_quotation( $order_id ) {
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...
381
382
		$status = true;
383
		$order_id = (int) $order_id;
384
		$order_meta = get_post_meta( $order_id, '_order_postmeta', true );
385
		$order_info = get_post_meta( $order_id, '_order_info', true );
386
		$_SESSION['shipping_method'] = isset( $order_meta['order_payment']['shipping_method'] ) ? $order_meta['order_payment']['shipping_method'] : 'No Shipping method required';
387
		if ( isset( $order_info['billing']['address_id'] ) ) {
388
			$_SESSION['billing_address'] = $order_info['billing']['address_id'];
389
			$_SESSION['cart'] = $order_meta;
390
			$_SESSION['cart']['order_id'] = $order_id;
391
    		$_SESSION['cart']['cart_type'] = 'cart';
392
			$_SESSION['cart']['order_shipping_cost_fixe'] = 'on';
393
			$permalink = get_permalink( get_option( 'wpshop_cart_page_id' ) ) . '?order_step=5';
394
		} else {
395
			$status = self::add_order_to_session( $order_id );
396
			$permalink = get_permalink( wpshop_tools::get_page_id( get_option( 'wpshop_checkout_page_id' ) ) );
397
		}
398
		return array( 'status' => $status, 'permalink' => $permalink );
399
	}
400
401
	/**
402
	 * Add order to SESSION.
403
	 *
404
	 * @method add_order_to_session
405
	 * @param  int $order_id Id of order.
406
	 */
407
	public static function add_order_to_session( $order_id ) {
408
409
		$order_meta = get_post_meta( $order_id, '_order_postmeta', true );
410
		if ( $order_meta != false ) {
411
			$_SESSION['cart'] = array();
412
			$_SESSION['cart']['order_amount_to_pay_now'] = $order_meta['order_amount_to_pay_now'];
413
			$_SESSION['cart']['order_items'] = array();
414
			if ( ! empty( $order_meta ) && ! empty( $order_meta['order_items'] ) ) {
415
				$wpshop_cart_type = 'cart';
0 ignored issues
show
Unused Code introduced by
$wpshop_cart_type is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
416
				foreach ( $order_meta['order_items'] as $item ) {
417
					$_SESSION['cart']['order_items'][ $item['item_id'] ] = $item;
418
				}
419
				$wps_cart_ctr = new wps_cart();
420
				$order = $wps_cart_ctr->calcul_cart_information( array() );
421
				$wps_cart_ctr->store_cart_in_session( $order );
422
			}
423
			$_SESSION['order_id'] = $order_id;
424
		}
425
		return (bool) ($order_meta != false);
426
	}
427
	/**
428
	 * AJAX - Delete order by order_id
429
	 */
430
	public function wps_delete_order() {
431
432
		$_wpnonce = ! empty( $_REQUEST['_wpnonce'] ) ? sanitize_text_field( $_REQUEST['_wpnonce'] ) : '';
433
		if ( ! wp_verify_nonce( $_wpnonce, 'wps_delete_order' ) ) {
434
				wp_die();
435
		}
436
437
		$status = false;
438
		$output = '';
439
		$order_id = ! empty( $_POST['order_id'] ) ? (int) $_POST['order_id'] : 0;
440
		if ( $order_id ) {
441
			$order_meta = get_post_meta( $order_id, '_order_postmeta', true );
442
			$wps_credit = new wps_credit();
443
			$wps_credit->create_an_credit( $order_id );
444
			$order_meta['order_status'] = 'canceled';
445
			$order_meta['order_payment']['refunded_action']['refunded_date'] = current_time( 'mysql', 0 );
446
			$order_meta['order_payment']['refunded_action']['author'] = get_current_user_id();
447
			update_post_meta( $order_id, '_order_postmeta', $order_meta );
448
			ob_start();
449
			require( wpshop_tools::get_template_part( WPS_ORDERS_DIR, $this->template_dir, 'frontend', 'order_row_in_account' ) );
450
			$output = ob_get_contents();
451
			ob_end_clean();
452
			$status = true;
453
		}
454
		echo json_encode( array( 'status' => $status, 'row' => $output ) );
455
		wp_die();
456
	}
457
458
	/**
459
	 * Create an hash with SiteUrl + OrderID + CustomerID + YearMonth.
460
	 *
461
	 * @method wps_token_order_customer
462
	 * @param  int $order_id OrderID.
463
	 * @return mixed sha1 or false.
464
	 */
465
	public static function wps_token_order_customer( $order_id, $date = null ) {
466
		$date = isset( $date ) ? $date : date( 'Ym' );
467
		$order_metadata = get_post_meta( $order_id, '_order_postmeta', true );
468
		if ( ! isset( $order_metadata['customer_id'] ) ) {
469
			return false;
470
		}
471
		return sha1( site_url() . '_' . $order_id . '_' . $order_metadata['customer_id'] . '_' . $date );
472
	}
473
474
	/**
475
	 * Verify hash from wps_token_order_customer for 2 months
476
	 *
477
	 * @method	wps_verify_token_order
478
	 * @param	string $token		Entry token.
479
	 * @param	int    $order_id	OrderID.
480
	 * @return	boolean
481
	 */
482
	public static function wps_verify_token_order( $token, $order_id ) {
483
		$current_month = self::wps_token_order_customer( $order_id );
484
		$last_month = self::wps_token_order_customer( $order_id, date_format( date_create( date( 'Y-m' ) . ' - 1month' ), 'Ym' ) );
485
		return (bool) ( (bool) $current_month && (bool) $last_month && ( $token === $current_month || $token === $last_month ) );
486
	}
487
}
488