Completed
Push — master ( fba304...e3db56 )
by
unknown
38:37
created

wpshop_orders   F

Complexity

Total Complexity 160

Size/Duplication

Total Lines 651
Duplicated Lines 20.89 %

Coupling/Cohesion

Components 0
Dependencies 6

Importance

Changes 0
Metric Value
dl 136
loc 651
rs 1.4178
c 0
b 0
f 0
wmc 160
lcom 0
cbo 6

16 Methods

Rating   Name   Duplication   Size   Complexity  
B create_orders_type() 34 34 1
C list_table_filters() 0 22 8
F list_table_filter_parse_query() 51 101 28
C latest_products_ordered() 0 36 15
A get_order_list_for_customer() 0 18 3
B add_meta_boxes() 3 28 2
F order_actions() 0 100 31
A order_container_in_admin() 0 7 1
A order_content() 0 16 3
A order_generate_billing_number() 0 17 4
A get_new_order_reference() 17 17 3
A get_new_pre_order_reference() 19 19 4
B set_order_customer_addresses() 0 25 6
A orders_edit_columns() 0 15 1
D orders_custom_columns() 12 114 46
A display_customer_pay_quotation() 0 9 4

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like wpshop_orders often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use wpshop_orders, and based on these observations, apply Extract Interface, too.

1
<?php if ( !defined( 'ABSPATH' ) ) exit;
2
/**
3
 * Products management method file
4
 *
5
 * This file contains the different methods for products management
6
 * @author Eoxia <[email protected]>
7
 * @version 1.1
8
 * @package wpshop
9
 * @subpackage librairies
10
 */
11
12
/*	Check if file is include. No direct access possible with file url	*/
13
if ( !defined( 'WPSHOP_VERSION' ) ) {
14
	die( __('Access is not allowed by this way', 'wpshop') );
15
}
16
17
/**
18
 * This file contains the different methods for products management
19
 * @author Eoxia <[email protected]>
20
 * @version 1.1
21
 * @package wpshop
22
 * @subpackage librairies
23
 */
24
class wpshop_orders {
25
26
	/**
27
	 * Create a new custom post type in wordpress for current element
28
	 */
29 View Code Duplication
	public static function create_orders_type( ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
30
		register_post_type(WPSHOP_NEWTYPE_IDENTIFIER_ORDER, array(
31
			'labels' => array(
32
				'name' 					=> __('Orders', 'wpshop'),
33
				'singular_name' 		=> __('Order', 'wpshop'),
34
				'add_new' 				=> __('Add quotation', 'wpshop'),
35
				'add_new_item' 			=> __('Add new quotation', 'wpshop'),
36
				'edit' 					=> __('Edit', 'wpshop'),
37
				'edit_item' 			=> __('Edit Order', 'wpshop'),
38
				'new_item' 				=> __('New quotation', 'wpshop'),
39
				'view' 					=> __('View Order', 'wpshop'),
40
				'view_item' 			=> __('View Order', 'wpshop'),
41
				'search_items' 			=> __('Search Orders', 'wpshop'),
42
				'not_found' 			=> __('No Orders found', 'wpshop'),
43
				'not_found_in_trash' 	=> __('No Orders found in trash', 'wpshop'),
44
				'parent' 				=> __('Parent Orders', 'wpshop')
45
			),
46
			'description' 			=> __('This is where store orders are stored.', 'wpshop'),
47
			'public' 				=> true,
48
			'show_ui' 				=> true,
49
			'capability_type' 		=> 'post',
50
			'publicly_queryable' 	=> false,
51
			'exclude_from_search' 	=> true,
52
			'show_in_menu' 			=> true,
53
			'hierarchical' 			=> false,
54
			'show_in_nav_menus' 	=> false,
55
			'show_in_admin_bar'   	=> false,
56
			'rewrite' 				=> false,
57
			'query_var' 			=> true,
58
			'supports' 				=> array(''),
59
			'has_archive' 			=> false,
60
			'menu_icon'				=> 'dashicons-cart'
61
		));
62
	}
63
64
	/**
65
	 *	Call the different boxes in edition page
66
	 */
67
	public static function add_meta_boxes( ) {
68
		global $post;
69
70
		/**	Add action button	*/
71
		add_meta_box(
72
			'wpshop_order_actions',
73
			'<span class="dashicons dashicons-info"></span> '.__('Actions on order', 'wpshop'),
74
			array('wpshop_orders', 'order_actions'),
75
				WPSHOP_NEWTYPE_IDENTIFIER_ORDER, 'side', 'high'
76
		);
77
78 View Code Duplication
		if ( !in_array( $post->post_status, array( 'auto-draft' ) ) ) {
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...
79
			add_meta_box('wpshop_credit_actions', __('Credit on order', 'wpshop'), array('wps_credit', 'wps_credit_meta_box'), WPSHOP_NEWTYPE_IDENTIFIER_ORDER, 'side', 'low');
80
		}
81
82
83
84
		/**	Box	containing listing of customer notification */
85
// 		$notifs = self::get_notification_by_object( array('object_type' => 'order', 'object_id' => $post->ID) );
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
86
// 		if ( !empty($notifs) ) {
87
// 			add_meta_box(
88
// 				'wpshop_order_customer_notification',
89
// 				__('Customer Notification', 'wpshop'),
90
// 				array('wpshop_orders', 'wpshop_order_customer_notification'),
91
// 					WPSHOP_NEWTYPE_IDENTIFIER_ORDER, 'side', 'low'
92
// 			);
93
// 		}
94
	}
95
96
97
98
	/**
99
	 * Define the box for actions on order
100
	 *
101
	 * @param object $order The current order being edited
102
	 */
103
	public static function order_actions( $order ) {
104
		$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...
105
106
		$order_status = unserialize(WPSHOP_ORDER_STATUS);
107
		$order_postmeta = get_post_meta($order->ID, '_order_postmeta', true);
108
109
		$tpl_component = array();
110
111
		$delete_button = wpshop_display::display_template_element('wpshop_admin_order_action_del_button', array('ADMIN_ORDER_DELETE_LINK' => esc_url( get_delete_post_link($order->ID) ) , 'ADMIN_ORDER_DELETE_TEXT' => (!EMPTY_TRASH_DAYS ? __('Delete Permanently', 'wpshop') :  __('Move to Trash', 'wpshop'))), array(), 'admin');
112
		$tpl_component['ADMIN_ORDER_DELETE_ORDER'] = current_user_can( "delete_post", $order->ID ) ? $delete_button : '';
113
114
		/**	Add an action list	*/
115
		$tpl_component['ADMIN_ORDER_ACTIONS_LIST'] = '';
116
117
		/**	Display main information about the order	*/
118
		$order_main_info = '';
119
		if(!empty($order_postmeta['order_date'])){
120
			$order_main_info .=  '<div class="wps-product-section"><span class="dashicons dashicons-calendar-alt"></span> <strong>'.__('Order date','wpshop').' : </strong><br/>'.mysql2date('d F Y H:i:s', $order_postmeta['order_date'], true).'</div>';
121
		}
122
		$order_main_info .= '<div class="wps-product-section">';
123
		if(empty($order_postmeta['order_date']) || (empty($order_postmeta['order_key']) && empty($order_postmeta['order_temporary_key']) && empty($order_postmeta['order_invoice_ref']))){
124
			$order_main_info .=  '<span class="dashicons dashicons-arrow-right"></span> <strong>'.__('Temporary quotation reference','wpshop').': </strong>'.self::get_new_pre_order_reference(false).'<br/>';
125
		}
126
		else{
127
			if(!empty($order_postmeta['order_key'])){
128
				$order_main_info .=  '<span class="dashicons dashicons-arrow-right"></span> <strong>'.__('Order reference','wpshop').' : </strong>'.$order_postmeta['order_key'].'<br/>';
129
			}
130
			if(!empty($order_postmeta['order_temporary_key'])){
131
				$order_main_info .=  '<span class="dashicons dashicons-arrow-right"></span> <strong>'.__('Pre-order reference','wpshop').': </strong>'.$order_postmeta['order_temporary_key'].'<br/>';
132
				$post_ID = !empty( $_GET['post'] ) ? (int) $_GET['post'] : 0;
133
				$order_main_info .= '<a href="' .admin_url( 'admin-post.php?action=wps_invoice&order_id=' . $post_ID . '&mode=pdf' ) . '">' .__('Download the quotation', 'wpshop'). '</a><br />';
134
			}
135
			if(!empty($order_postmeta['order_invoice_ref'])){
136
				$sub_tpl_component = array();
0 ignored issues
show
Unused Code introduced by
$sub_tpl_component 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...
137
				$order_invoice_download = '<a href="' . admin_url( 'admin-post.php?action=wps_invoice&order_id=' . $order->ID . '&invoice_ref=' . $order_postmeta['order_invoice_ref'] . '&mode=pdf' ) . '">' . __('Download invoice', 'wpshop') . '</a><br />';
138
				$order_main_info .= '<span class="dashicons dashicons-arrow-right"></span> <strong>'. __('Invoice number','wpshop').': </strong>'.$order_postmeta['order_invoice_ref'].'<br/>' . $order_invoice_download . '';
139
			}
140
			else {
141
				$order_main_info .= wpshop_display::display_template_element('wpshop_admin_order_generate_invoice_button', array(), array(), 'admin');
142
			}
143
		}
144
		$order_main_info .= '</div>';
145
146
147
		/*Add the current order status in display**/
148
			$tpl_component['ADMIN_ORDER_ACTIONS_LIST'] .= ( !empty($order_postmeta['order_status']) ) ? (sprintf('<span class="order_status_' . $order->ID . ' wpshop_order_status_container wpshop_order_status_%1$s ">%2$s</span>', sanitize_title(strtolower($order_postmeta['order_status'])), __($order_status[strtolower($order_postmeta['order_status'])], 'wpshop')) ) : '';
149
150
			$tpl_component['ADMIN_ORDER_ACTIONS_LIST'] .= $order_main_info;
151
152
		/**	Add a box allowing to notify the customer on order update	*/
153
		/**
154
		 *
155
		 * To check because notification is not really send
156
		 *
157
		 */
158
		/*if ( !empty($order->post_author) ) {
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...
159
			$tpl_component['ADMIN_ORDER_ACTIONS_LIST'] .= '
160
			<div class="wps-product-section wpshop_order_notify_customer_on_update_container" >
161
				<input type="checkbox" name="notif_the_customer" id="wpshop_order_notif_the_customer_on_update" /> <label for="wpshop_order_notif_the_customer_on_update" >'.__('Send a notification to the customer', 'wpshop').'</label>
162
				<!-- <br/><input type="checkbox" name="notif_the_customer_sendsms" id="wpshop_order_notif_the_customer_sendsms_on_update" /> <label for="wpshop_order_nnotif_the_customer_sendsms_on_update" >'.__('Send a SMS to the customer', 'wpshop').'</label> -->
163
			</div>';
164
		}*/
165
166
		if( ( ( !empty($order_postmeta['cart_type']) && $order_postmeta['cart_type'] == 'quotation' ) || !empty( $order_postmeta['order_temporary_key'] ) ) && in_array( $order_postmeta['order_status'], array( 'awaiting_payment', 'partially_paid' ) ) && (float) $order_postmeta['order_amount_to_pay_now'] != (float) 0 ) {
167
			$tpl_component['ADMIN_ORDER_ACTIONS_LIST'] .= '<div class="wps-product-section">' . self::display_customer_pay_quotation( isset( $order_postmeta['pay_quotation'] ), $order->ID ) . '</div>';
168
		}
169
170
		/**
171
		 * Only for quotations
172
		 */
173
		/*if( ( ( !empty($order_postmeta['cart_type']) && $order_postmeta['cart_type'] == 'quotation' ) || !empty( $order_postmeta['order_temporary_key'] ) ) && $order_postmeta['order_status'] != 'canceled' && (float) $order_postmeta['order_amount_to_pay_now'] != (float) 0 ) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% 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...
174
			$tpl_component['ADMIN_ORDER_ACTIONS_LIST'] .= '<div class="wps-product-section"><input type="text" value="' . wpshop_checkout::wps_direct_payment_link_url( $order->ID ) . '"/></div>';
175
		}*/
176
177
		/*Add the button regarding the order status**/
178
		if ( !empty($order_postmeta['order_status']) ) {
179
			if( $order_postmeta['order_status'] == 'awaiting_payment' ) {
180
				$tpl_component['ADMIN_ORDER_ACTIONS_LIST'] .= '<div class="wps-product-section"><button class="wps-bton-second-mini-rounded markAsCanceled order_'.$order->ID.'" >'.__('Cancel this order', 'wpshop').'</button><input type="hidden" id="markascanceled_order_hidden_indicator" name="markascanceled_order_hidden_indicator" /></div>';
181
			}
182
			$credit_meta = get_post_meta( $order->ID, '_wps_order_credit', true );
183
184
			$total_received = (float) 0;
185
			if ( ! empty( $order_postmeta['order_payment'] ) && ! empty( $order_postmeta['order_payment']['received'] ) ) {
186
				foreach( $order_postmeta['order_payment']['received'] as $received ) {
187
					$total_received += (float) isset( $received['received_amount'] ) ? $received['received_amount'] : 0;
188
				}
189
			}
190
191
			if ( empty($credit_meta) && (float) 0 !== $total_received ) {
192
				if( $order_postmeta['order_status'] == 'refunded') {
193
					$tpl_component['ADMIN_ORDER_ACTIONS_LIST'] .= '<div class="wps-product-section wps_markAsRefunded_container">' .__('Credit Slip number', 'wpshop'). ' : <strong>'. ( (!empty($order_postmeta) && !empty($order_postmeta['order_payment']) && !empty($order_postmeta['order_payment']['refunded_action']) && !empty($order_postmeta['order_payment']['refunded_action']['credit_slip_ref']) ) ? '<a href="' .admin_url( 'admin-post.php?action=wps_invoice&order_id=' .$order->ID. '&amp;invoice_ref=' .$order_postmeta['order_payment']['refunded_action']['credit_slip_ref'].'&credit_slip=ok' ). '" target="_blank">'.$order_postmeta['order_payment']['refunded_action']['credit_slip_ref'].'</a>' : '') .'</strong></div>';
194
				}
195
				else {
196
					$tpl_component['ADMIN_ORDER_ACTIONS_LIST'] .= '<div class="wps-product-section wps_markAsRefunded_container" ><button class="wps-bton-second-mini-rounded markAsRefunded order_' .$order->ID. '">' .__('Refund this order', 'wpshop'). '</button><input type="hidden" id="markasrefunded_order_hidden_indicator" name="markasrefunded_order_hidden_indicator" /></div>';
197
				}
198
			}
199
		}
200
		$tpl_component['ADMIN_ORDER_ACTIONS_LIST'] = strrev( preg_replace( strrev( '/wps-product-section/' ), '', strrev( $tpl_component['ADMIN_ORDER_ACTIONS_LIST'] ), 1 ) );
201
		echo wpshop_display::display_template_element( 'wpshop_admin_order_action_box', $tpl_component, array( 'type' => WPSHOP_NEWTYPE_IDENTIFIER_ORDER, 'id' => $order->ID ), 'admin' );
202
	}
203
204
205
206
	function order_container_in_admin() {
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...
207
		global $post;
208
		$output  = '<div id="wps_order_content_container">';
209
		$output .= self::order_content( $post );
210
		$output .= '</div>';
211
		echo $output;
212
	}
213
214
215
	/**
216
	 * Display the order content: the list of element put into order
217
	 *
218
	 * @param order $post The complete order content
219
	 */
220
	function order_content( $post ) {
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...
221
		$order_content = '';
222
223
		$order = get_post_meta($post->ID, '_order_postmeta', true);
224
225
		$order_content .= '<div id="order_product_container" class="order_product_container wpshop_cls" >';
226
		if($order){/*	Read the order content if the order has product	*/
227
			$order_content .= '<input type="hidden" value="" name="order_products_to_delete" id="order_products_to_delete" />' . wpshop_cart::display_cart(true, $order, 'admin');
228
			if (empty($order['order_invoice_ref'])) {
229
				$order_content .= '<div id="order_refresh_button_container" class="wpshop_clear_block" ><input type="button" class="button-primary alignright wpshopHide" id="wpshop_admin_order_recalculate" value="' . __('Refresh order informations', 'wpshop') . '" /></div>';
230
			}
231
		}
232
		$order_content .= '<div class="wpshop_cls" ></div></div>';
233
234
		return $order_content;
235
	}
236
237
238
239
240
241
	/** Generate the billing reference regarding the order $order_id
242
	 * @return void
243
	*/
244
	function order_generate_billing_number($order_id, $force_invoicing = false){
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...
245
		global $wpdb, $wpshop_modules_billing;
246
247
		// Get the order from the db
248
		$order = get_post_meta($order_id, '_order_postmeta', true);
249
250
		// If the payment is completed
251
		if(($order['order_status']=='completed') || $force_invoicing) {
252
253
			// If the reference hasn't been generated yet
254
			if(empty($order['order_invoice_ref'])) {
255
				$order['order_invoice_ref'] = $wpshop_modules_billing->generate_invoice_number( $order_id );
256
257
				update_post_meta($order_id, '_order_postmeta', $order);
258
			}
259
		}
260
	}
261
262
263
	/** Renvoi une nouvelle r�f�rence unique pour une commande
264
	* @return int
265
	*/
266 View Code Duplication
	public static function get_new_order_reference(){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
267
		$number_figures = get_option('wpshop_order_number_figures', false);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a integer.

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...
268
		/* If the number doesn't exist, we create a default one */
269
		if(!$number_figures){
270
			$number_figures = 5;
271
			update_option('wpshop_order_number_figures', $number_figures);
272
		}
273
274
		$order_current_number = get_option('wpshop_order_current_number', false);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a integer.

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...
275
		/* If the counter doesn't exist, we initiate it */
276
		if(!$order_current_number) { $order_current_number = 1; }
277
		else { $order_current_number++; }
278
		update_option('wpshop_order_current_number', $order_current_number);
279
280
		$order_ref = (string)sprintf('%0'.$number_figures.'d', $order_current_number);
281
		return WPSHOP_ORDER_REFERENCE_PREFIX.$order_ref;
282
	}
283
284
	/** Renvoi une nouvelle r�f�rence unique pour un devis
285
	* @return int
286
	*/
287 View Code Duplication
	public static function get_new_pre_order_reference($save = true){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
288
		$number_figures = get_option('wpshop_order_number_figures', false);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a integer.

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...
289
		/* If the number doesn't exist, we create a default one */
290
		if(!$number_figures){
291
			$number_figures = 5;
292
			update_option('wpshop_order_number_figures', $number_figures);
293
		}
294
295
		$order_current_number = get_option('wpshop_preorder_current_number', false);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a integer.

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...
296
		/* If the counter doesn't exist, we initiate it */
297
		if(!$order_current_number) { $order_current_number = 1; }
298
		else { $order_current_number++; }
299
		if($save){
300
			update_option('wpshop_preorder_current_number', $order_current_number);
301
		}
302
303
		$order_ref = (string)sprintf('%0'.$number_figures.'d', $order_current_number);
304
		return WPSHOP_PREORDER_REFERENCE_PREFIX.$order_ref;
305
	}
306
307
308
309
310
311
	/**
312
	 *	Add information about user to the selected order
313
	 *
314
	 *	@param int $user_id The user identifier to get information for and to add to order meta informations
315
	 *	@param int $order_id The order identifier to update meta information for
316
	 *
317
	 *	@return void
318
	 */
319
	public static function set_order_customer_addresses($user_id, $order_id, $shipping_address_id='', $billing_address_id=''){
0 ignored issues
show
Unused Code introduced by
The parameter $user_id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
320
		/**	Get order informations	*/
321
		$billing_info['id'] = get_post_meta($billing_address_id, WPSHOP_ADDRESS_ATTRIBUTE_SET_ID_META_KEY, true);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$billing_info was never initialized. Although not strictly required by PHP, it is generally a good practice to add $billing_info = 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...
322
		$billing_info['address'] = get_post_meta($billing_address_id, '_'.WPSHOP_NEWTYPE_IDENTIFIER_ADDRESS.'_metadata', true);
323
		$billing_info['address_id'] = ( !empty($_SESSION['billing_address']) ) ? intval( $_SESSION['billing_address'] ) : '';
324
		if ( !empty($_SESSION['shipping_partner_id']) ) {
325
			$partner_address_id = get_post_meta( $_SESSION['shipping_partner_id'], '_wpshop_attached_address', true);
326
			if (!empty($partner_address_id)) {
327
				foreach( $partner_address_id as $address_id ) {
328
					$shipping_info['id'] = get_post_meta($address_id, WPSHOP_ADDRESS_ATTRIBUTE_SET_ID_META_KEY, true);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$shipping_info was never initialized. Although not strictly required by PHP, it is generally a good practice to add $shipping_info = 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...
329
					$shipping_info['address'] = get_post_meta( $address_id, '_'.WPSHOP_NEWTYPE_IDENTIFIER_ADDRESS.'_metadata', true);
330
				}
331
			}
332
		}
333
		else {
334
			$shipping_info['id'] = get_post_meta($shipping_address_id, WPSHOP_ADDRESS_ATTRIBUTE_SET_ID_META_KEY, true);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$shipping_info was never initialized. Although not strictly required by PHP, it is generally a good practice to add $shipping_info = 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...
335
			$shipping_info['address'] = get_post_meta($shipping_address_id, '_'.WPSHOP_NEWTYPE_IDENTIFIER_ADDRESS.'_metadata', true);
336
			$shipping_info['address_id'] = ( !empty($_SESSION['shipping_address']) ) ? intval( $_SESSION['shipping_address'] ) : '';
337
		}
338
339
		$order_info = array('billing' => $billing_info, 'shipping' => $shipping_info);
0 ignored issues
show
Bug introduced by
The variable $shipping_info 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...
340
341
		/**	Update order info metadata with new shipping	*/
342
		update_post_meta($order_id, '_order_info', $order_info);
343
	}
344
345
346
	/** Set the custom colums
347
	 * @return array
348
	*/
349
	static function orders_edit_columns($columns){
0 ignored issues
show
Unused Code introduced by
The parameter $columns is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
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...
350
	  $columns = array(
351
		'cb' => '<input type="checkbox" />',
352
		'order_identifier' => __('Identifiers', 'wpshop'),
353
		'order_status' => __('Status', 'wpshop'),
354
		'order_type' => __('Order type', 'wpshop'),
355
		'order_billing' => __('Billing', 'wpshop'),
356
		'order_shipping' => __('Shipping', 'wpshop'),
357
		'order_total' => __('Order total', 'wpshop'),
358
		'date' => __('Date', 'wpshop'),
359
		//'order_actions' => __('Actions', 'wpshop')
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...
360
	  );
361
362
	  return $columns;
363
	}
364
365
	/** Give the content by column
366
	 * @return array
367
	*/
368
	public static function orders_custom_columns($column, $post_id) {
369
		if ( get_post_type( $post_id ) == WPSHOP_NEWTYPE_IDENTIFIER_ORDER ) {
370
			global $civility, $order_status;
371
372
			$metadata = get_post_custom();
373
374
			$order_postmeta = isset($metadata['_order_postmeta'][0])?unserialize($metadata['_order_postmeta'][0]):'';
375
			$addresses = get_post_meta($post_id,'_order_info', true);
376
377
			switch($column){
378
				case "order_identifier":
379
					if( !empty( $order_postmeta['order_key'] ) ) {
380
						echo '<b>' . $order_postmeta['order_key'] . '</b><br>';
381
					}
382
					if( !empty( $order_postmeta['order_invoice_ref'] ) ) {
383
						echo '<i>' . $order_postmeta['order_invoice_ref'] . '</i>';
384
					} elseif( !empty($order_postmeta['order_temporary_key'] ) ) {
385
						echo '<b>' . $order_postmeta['order_temporary_key'] . '</b>';
386
					}
387
				break;
388
389
				case "order_status":
390
					echo !empty($order_postmeta['order_status']) ? sprintf('<mark class="%s" id="order_status_'.$post_id.'">%s</mark>', sanitize_title(strtolower($order_postmeta['order_status'])), __($order_status[strtolower($order_postmeta['order_status'])], 'wpshop')) : __('Unknown Status', 'wpshop');
391
				break;
392
393
				case "order_billing":
394 View Code Duplication
					if ( !empty($addresses['billing']) && !empty($addresses['billing']['address']) && is_array($addresses['billing']['address']) ) {
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...
395
						$billing = $addresses['billing']['address'];
396
					}
397
					else if ( !empty($addresses['billing']) ) {
398
						$billing = $addresses['billing'];
399
					}
400
					if ( !empty($billing) ) {
401
						echo (!empty($billing['civility']) ? __(wpshop_attributes::get_attribute_type_select_option_info($billing['civility'], 'label', 'custom'), 'wpshop') : null).' <strong>'.(!empty($billing['address_first_name']) ? $billing['address_first_name'] : null).' '.(!empty($billing['address_last_name']) ? $billing['address_last_name'] : null).'</strong>';
402
						echo empty($billing['company']) ?'<br />' : ', <i>'.$billing['company'].'</i><br />';
403
						echo !empty($billing['address']) ? $billing['address'] : null;
404
						echo !empty($billing['postcode']) ? '<br />' . $billing['postcode'] . ' ' : null;
405
						echo !empty($billing['city']) ? $billing['city'] . ', ' : null;
406
						echo !empty($billing['country']) ? $billing['country'] : null;
407
						echo (!empty($billing['phone']) ? '<br /><b>' . $billing['phone'] . '</b>' : '');
408
					}
409
					else {
410
						echo __('No information available for user billing', 'wpshop');
411
					}
412
				break;
413
414
				case "order_shipping":
415 View Code Duplication
					if ( !empty($addresses['shipping']) && !empty($addresses['shipping']['address']) && is_array($addresses['shipping']['address']) ) {
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...
416
						$shipping = $addresses['shipping']['address'];
417
					}
418
					else if ( !empty($addresses['shipping']) ) {
419
						$shipping = $addresses['shipping'];
420
					}
421
					if ( !empty($shipping) ) {
422
						echo '<strong>'.(!empty($shipping['address_first_name']) ? $shipping['address_first_name'] : null).' '.(!empty($shipping['address_last_name']) ? $shipping['address_last_name'] : null).'</strong>';
423
						echo empty($shipping['company'])?'<br />':', <i>'.$shipping['company'].'</i><br />';
424
						echo (!empty($shipping['address']) ? $shipping['address'] : null);
425
						echo !empty($billing['postcode']) ? '<br />' . $billing['postcode'] . ' ' : null;
0 ignored issues
show
Bug introduced by
The variable $billing seems only to be defined at a later point. As such the call to empty() seems to always evaluate to true.

This check marks calls to isset(...) or empty(...) that are found before the variable itself is defined. These will always have the same result.

This is likely the result of code being shifted around. Consider removing these calls.

Loading history...
426
						echo !empty($billing['city']) ? $billing['city'] . ', ' : null;
427
						echo !empty($billing['country']) ? $billing['country'] : null;
428
					}
429
					else{
430
						echo __('No information available for user shipping', 'wpshop');
431
					}
432
				break;
433
434
				case "order_type":
435
						echo '<a href="'.admin_url('post.php?post='.$post_id.'&action=edit').'">'.(!empty($order_postmeta['order_temporary_key']) ? __('Quotation','wpshop') :  __('Basic order','wpshop')).'</a>';
436
						$buttons = '<p class="row-actions">';
437
						// Voir la commande
438
						$buttons .= '<a class="button button-small" href="'.admin_url('post.php?post='.$post_id.'&action=edit').'">'.__('View', 'wpshop').'</a>';
439
						// Marquer comme envoy�
440
						if (!empty($order_postmeta['order_status']) && ($order_postmeta['order_status'] == 'completed')) {
441
							$buttons .= '<a data-id="' . $post_id . '" class="wps-bton-second-mini-rounded markAsShipped order_'.$post_id.' wps-bton-loader">'.__('Mark as shipped', 'wpshop').'</a> ';
442
						}
443
						else if (!empty($order_postmeta['order_status']) && ($order_postmeta['order_status'] == 'awaiting_payment' )) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
444
							//		$buttons .= '<a class="button markAsCompleted order_'.$post_id.' alignleft" >'.__('Payment received', 'wpshop').'</a>' . wpshop_payment::display_payment_receiver_interface($post_id) . ' ';
0 ignored issues
show
Unused Code Comprehensibility introduced by
46% 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...
445
						}
446
						$buttons .= '</p>';
447
						$buttons .= '<input type="hidden" name="input_wpshop_change_order_state" id="input_wpshop_change_order_state" value="' . wp_create_nonce("wpshop_change_order_state") . '" />';
448
						$buttons .= '<input type="hidden" name="input_wpshop_dialog_inform_shipping_number" id="input_wpshop_dialog_inform_shipping_number" value="' . wp_create_nonce("wpshop_dialog_inform_shipping_number") . '" />';
449
						$buttons .= '<input type="hidden" name="input_wpshop_validate_payment_method" id="input_wpshop_validate_payment_method" value="' . wp_create_nonce("wpshop_validate_payment_method") . '" />';
450
451
						echo $buttons;
452
					break;
453
454
				case "order_total":
455
					$currency = !empty($order_postmeta['order_currency']) ? $order_postmeta['order_currency'] : get_option('wpshop_shop_default_currency');
456
					echo isset( $order_postmeta['order_grand_total'] ) ? number_format( $order_postmeta['order_grand_total'], 2, '.', '' ).' '.  wpshop_tools::wpshop_get_sigle($currency) : 'NaN';
457
				break;
458
459
				/*case "order_actions":
0 ignored issues
show
Unused Code Comprehensibility introduced by
48% 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...
460
					$buttons = '<p class="row-actions">';
461
					// Marquer comme envoy�
462
					if (!empty($order_postmeta['order_status']) && ($order_postmeta['order_status'] == 'completed')) {
463
							$buttons .= '<a class="button markAsShipped order_'.$post_id.'">'.__('Mark as shipped', 'wpshop').'</a> ';
464
					}
465
					else if (!empty($order_postmeta['order_status']) && ($order_postmeta['order_status'] == 'awaiting_payment' )) {
466
					//		$buttons .= '<a class="button markAsCompleted order_'.$post_id.' alignleft" >'.__('Payment received', 'wpshop').'</a>' . wpshop_payment::display_payment_receiver_interface($post_id) . ' ';
467
					}
468
469
					// Voir la commande
470
					$buttons .= '<a class="button alignright" href="'.admin_url('post.php?post='.$post_id.'&action=edit').'">'.__('View', 'wpshop').'</a>';
471
					$buttons .= '</p>';
472
					$buttons .= '<input type="hidden" name="input_wpshop_change_order_state" id="input_wpshop_change_order_state" value="' . wp_create_nonce("wpshop_change_order_state") . '" />';
473
					$buttons .= '<input type="hidden" name="input_wpshop_dialog_inform_shipping_number" id="input_wpshop_dialog_inform_shipping_number" value="' . wp_create_nonce("wpshop_dialog_inform_shipping_number") . '" />';
474
					$buttons .= '<input type="hidden" name="input_wpshop_validate_payment_method" id="input_wpshop_validate_payment_method" value="' . wp_create_nonce("wpshop_validate_payment_method") . '" />';
475
476
					echo $buttons;
477
				break;*/
478
			}
479
480
		}
481
	}
482
483
	public static function list_table_filters() {
484
		$post_type = !empty( $_GET['post_type'] ) ? sanitize_text_field( $_GET['post_type'] ) : '';
485
		$entity_filter = !empty( $_GET['entity_filter'] ) ? sanitize_text_field( $_GET['entity_filter'] ) : '';
486
		$entity_filter_btpf = !empty( $_GET['entity_filter_btpf'] ) ? sanitize_text_field( $_GET['entity_filter_btpf'] ) : '';
487
		$entity_filter_btps = !empty( $_GET['entity_filter_btps'] ) ? sanitize_text_field( $_GET['entity_filter_btps'] ) : '';
488
489
		if (isset($post_type)) {
490
			if (post_type_exists($post_type) && ($post_type == WPSHOP_NEWTYPE_IDENTIFIER_ORDER)) {
491
				$filter_possibilities = array();
492
				$filter_possibilities['all'] = __('-- Select Filter --', 'wpshop');
493
				$filter_possibilities['only_orders'] = __('List orders only', 'wpshop');
494
				$filter_possibilities['quotations'] = __('List quotations only', 'wpshop');
495
				$filter_possibilities['free_orders'] = __('List orders free', 'wpshop');
496
				echo wpshop_form::form_input_select('entity_filter', 'entity_filter', $filter_possibilities, $entity_filter, '', 'index');
497
				$min = $entity_filter_btpf;
498
				$max = $entity_filter_btps;
499
				echo ' <label for="entity_filter_btpf">'.__('Between two prices', 'wpshop').'</label> ';
500
				echo wpshop_form::form_input('entity_filter_btpf', 'entity_filter_btpf', $min, 'text', 'placeholder="'.__('Minimum price', 'wpshop').'"', null);
501
				echo wpshop_form::form_input('entity_filter_btps', 'entity_filter_btps', $max, 'text', 'placeholder="'.__('Maximum price', 'wpshop').'"', null);
502
			}
503
		}
504
	}
505
506
	public static function list_table_filter_parse_query($query) {
507
		global $pagenow, $wpdb;
508
		$post_type = !empty( $_GET['post_type'] ) ? sanitize_text_field( $_GET['post_type'] ) : '';
509
		$entity_filter = !empty( $_GET['entity_filter'] ) ? sanitize_text_field( $_GET['entity_filter'] ) : '';
510
		$entity_filter_btpf = !empty( $_GET['entity_filter_btpf'] ) ? sanitize_text_field( $_GET['entity_filter_btpf'] ) : '';
0 ignored issues
show
Unused Code introduced by
$entity_filter_btpf 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...
511
		$entity_filter_btps = !empty( $_GET['entity_filter_btps'] ) ? sanitize_text_field( $_GET['entity_filter_btps'] ) : '';
0 ignored issues
show
Unused Code introduced by
$entity_filter_btps 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...
512
513
		if ( is_admin() && ($pagenow == 'edit.php') && !empty( $post_type ) && ( $post_type == WPSHOP_NEWTYPE_IDENTIFIER_ORDER ) && !empty( $entity_filter ) ) {
514
			$check = null;
515
			switch ( $entity_filter ) {
516
				case 'all':
517
					$sql_query = $wpdb->prepare(
518
						"SELECT ID
519
						FROM {$wpdb->posts}
520
						WHERE post_type = %s
521
						AND post_status != %s",
522
					WPSHOP_NEWTYPE_IDENTIFIER_ORDER,
523
					'auto-draft');
524
					$check = 'post__in';
525
					break;
526 View Code Duplication
				case 'only_orders':
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...
527
					$sql_query = $wpdb->prepare(
528
						"SELECT ID
529
						FROM {$wpdb->posts}
530
						INNER JOIN {$wpdb->postmeta}
531
						ON post_id = ID
532
						AND meta_key = %s
533
						AND meta_value NOT LIKE %s
534
						AND meta_value NOT LIKE %s
535
						WHERE post_type = %s
536
						AND post_status != %s",
537
					'_order_postmeta',
538
					'%s:9:"cart_type";s:9:"quotation";%',
539
					'%s:17:"order_grand_total";d:0;%',
540
					WPSHOP_NEWTYPE_IDENTIFIER_ORDER,
541
					'auto-draft');
542
					$check = 'post__in';
543
					break;
544 View Code Duplication
				case 'quotations':
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...
545
					$sql_query = $wpdb->prepare(
546
						"SELECT ID
547
						FROM {$wpdb->posts}
548
						INNER JOIN {$wpdb->postmeta}
549
						ON post_id = ID
550
						AND meta_key = %s
551
						AND meta_value LIKE %s
552
						WHERE post_type = %s
553
						AND post_status != %s",
554
					'_order_postmeta',
555
					'%s:9:"cart_type";s:9:"quotation";%',
556
					WPSHOP_NEWTYPE_IDENTIFIER_ORDER,
557
					'auto-draft');
558
					$check = 'post__in';
559
					break;
560 View Code Duplication
				case 'free_orders':
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...
561
					$sql_query = $wpdb->prepare(
562
							"SELECT ID
563
							FROM {$wpdb->posts}
564
							INNER JOIN {$wpdb->postmeta}
565
							ON post_id = ID
566
							AND meta_key = %s
567
							AND meta_value LIKE %s
568
							WHERE post_type = %s
569
							AND post_status != %s",
570
						'_order_postmeta',
571
						'%s:17:"order_grand_total";d:0;%',
572
						WPSHOP_NEWTYPE_IDENTIFIER_ORDER,
573
						'auto-draft');
574
						$check = 'post__in';
575
						$no_btp = 'yes';
576
						break;
577
			}
578
579
			if ( !empty( $check ) ) {
580
				if( !empty($no_btp) && $no_btp == 'yes' ) {
581
					$min = 'minimum';
582
					$max = 'maximum';
583
				} else {
584
					$min = ( !empty($_GET['entity_filter_btpf']) && is_numeric($_GET['entity_filter_btpf']) ) ? sanitize_text_field( $_GET['entity_filter_btpf'] ) : 'minimum';
585
					$max = ( !empty($_GET['entity_filter_btps']) && is_numeric($_GET['entity_filter_btps']) ) ? sanitize_text_field( $_GET['entity_filter_btps'] ) : 'maximum';
586
				}
587
				$results = $wpdb->get_results($sql_query);
0 ignored issues
show
Bug introduced by
The variable $sql_query 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...
588
				$post_id_list = array();
589
				$i = 0;
0 ignored issues
show
Unused Code introduced by
$i 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...
590
				foreach($results as $item){
591
					$meta_value = get_post_meta($item->ID, '_order_postmeta');
592
					$price = ( !empty( $meta_value[0]['order_grand_total'] ) ) ? $meta_value[0]['order_grand_total'] : '';
593
					if( $price >= $min || $min == 'minimum' ) {
594
						if( $price <= $max || $max == 'maximum' ) {
595
							$post_id_list[] = $item->ID;
596
						}
597
					}
598
				}
599
				if( empty($post_id_list) ) {
600
					$post_id_list[] = 'no_result';
601
				}
602
				$query->query_vars[$check] = $post_id_list;
603
			}
604
			$query->query_vars['post_type'] = WPSHOP_NEWTYPE_IDENTIFIER_ORDER;
605
		}
606
	}
607
608
609
610
	function latest_products_ordered ( $orders ) {
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...
611
		global $wpdb;
612
		$product_id = $output = '';
0 ignored issues
show
Unused Code introduced by
$product_id 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...
613
		$products = array();
614
		$display_option = get_option('wpshop_display_option');
615
		if ( !empty($orders) && !empty($display_option) && !empty($display_option['latest_products_ordered']) ) {
616
			foreach( $orders as $order ) {
617
				$order_content = get_post_meta( $order->ID, '_order_postmeta', true );
618
				if ( !empty($order_content) && !empty( $order_content['order_items']) ) {
619
620
					foreach( $order_content['order_items'] as $item ) {
621
						if ( count( $products) >= $display_option['latest_products_ordered'] ) {
622
							continue;
623
						}
624
						$product_id = $item['item_id'];
625
						if ( !empty( $item) && !empty($item['item_meta']) && !empty($item['item_meta']['variation_definition']) ) {
626
							$parent_def = wpshop_products::get_parent_variation( $item['item_id'] );
627
							if ( !empty( $parent_def ) ) {
628
								$parent_post = $parent_def['parent_post'];
629
								$product_id = $parent_post->ID;
630
							}
631
						}
632
633
						if ( !in_array($product_id, $products) ) {
634
							$products[] = $product_id;
635
						}
636
					}
637
				}
638
			}
639
			if ( !empty($products) ) {
640
				$products_id = implode(",", $products);
641
				$output = wpshop_display::display_template_element('latest_products_ordered', array('LATEST_PRODUCTS_ORDERED' => do_shortcode('[wpshop_products pid="' .$products_id. '"]')) );
642
			}
643
		}
644
		return $output;
645
	}
646
647
	function get_order_list_for_customer( $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...
648
		global $wpdb;
649
		$output = '';
650
651
		if( !empty($customer_id) ) {
652
			 $query = $wpdb->prepare( 'SELECT *
653
							 		   FROM ' .$wpdb->posts. '
654
							 		   WHERE post_author = %d
655
							 		   AND post_type = %s', $customer_id, WPSHOP_NEWTYPE_IDENTIFIER_CUSTOMERS );
656
			 $orders = $wpdb->get_results( $query );
657
658
			 foreach( $orders as $order ) {
0 ignored issues
show
Unused Code introduced by
This foreach statement is empty and can be removed.

This check looks for foreach loops that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

Consider removing the loop.

Loading history...
659
660
			 }
661
		}
662
663
		return $output;
664
	}
665
	static function display_customer_pay_quotation( $state, $oid ) {
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...
666
		$label = ( ( $state ) ? __('Invalid quotation', 'wpshop') : __('Valid quotation', 'wpshop') );
667
		$btn = '<p><a role="button" data-nonce="' . wp_create_nonce( 'wps_quotation_is_payable_by_customer' ) . '" class="wps-bton-' . ( ( $state ) ? 'third' : 'second' ) . '-mini-rounded quotation_is_payable_by_customer" href="#" >'.$label.'</a></p>';
668
		if( $state ) {
669
			//$btn .= '<a target="_blank" href="' . admin_url( 'admin-ajax.php?action=wps_checkout_quotation&order_id=' . $oid . '&is_link=link' ) . '">' . __( 'Pay link', 'wpshop' ) . '</a>';
670
			$btn .= '<span><input id="wps_direct_link_url" type="text" value="' . wpshop_checkout::wps_direct_payment_link_url( $oid ) . '"/><a class="button" data-copy-target="#wps_direct_link_url" title="' . __( 'Copy', 'wpshop' ) . '"><span class="dashicons dashicons-clipboard"></span></a><a data-nonce="' . wp_create_nonce( 'wps_send_direct_payment_link' ) . '" role="button" class="button" href="#" title="' . __( 'Send by mail', 'wpshop' ) . '"><span class="dashicons dashicons-email"></span></a></span><span>' . sprintf( __( 'Link is valid until %s', 'wpshop' ), mysql2date( get_option( 'date_format' ), date_format( date_create( date('Y-m') . ' + 2month - 1day' ), 'Y-m-d H:i:s' ), true ) ) . '</span>';
671
		}
672
		return $btn;
673
	}
674
}
675