Completed
Push — master ( eef885...465d0c )
by
unknown
30:08 queued 12:49
created

wpshop_attributes   F

Complexity

Total Complexity 706

Size/Duplication

Total Lines 3268
Duplicated Lines 10.34 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 0
Metric Value
dl 338
loc 3268
rs 3.9999
c 0
b 0
f 0
wmc 706
lcom 1
cbo 11

40 Methods

Rating   Name   Duplication   Size   Complexity  
A setMessage() 0 3 1
A getListingSlug() 0 3 1
A getEditionSlug() 0 3 1
A getDbTable() 0 3 1
B pageTitle() 6 19 10
D elementList() 7 71 13
F elementEdition() 111 604 102
B getPageFormButton() 5 20 9
C getElement() 0 38 8
F saveAttributeForEntity() 0 137 33
C getAttributeValueForEntityInSet() 0 52 13
B getElementWithAttributeAndValue() 0 55 9
B get_attribute_list_for_item() 0 42 2
C check_attribute_display() 0 23 21
F wpshop_att_val_func() 0 54 17
F get_attribute_field_definition() 8 222 78
F display_attribute() 6 58 13
D attribute_of_entity_to_tab() 0 133 21
D wps_attribute_values_display() 0 43 11
A wpshop_attributes_shortcode() 0 12 2
D entities_attribute_box() 0 140 25
D get_select_output() 9 79 21
B get_affected_value_for_list() 0 32 3
B get_attribute_option_output() 0 16 7
B get_attribute_option_fields() 0 23 4
A get_attribute_value_content() 0 10 2
C attribute_type_date_config() 0 76 9
D setAttributesValuesForItem() 0 54 12
C get_attribute_type_select_option_info() 0 42 7
A get_select_option_list_() 0 16 1
F get_select_options_list() 62 176 48
D get_attribute_list() 0 83 17
A get_attribute_list_in_same_set_section() 0 21 1
B get_variation_available_attribute() 0 35 5
C get_variation_available_attribute_display() 0 46 12
C get_variation_attribute() 4 35 7
A get_attribute_user_defined() 0 19 1
A quick_edit() 0 17 3
A bulk_edit() 0 18 3
F elementAction() 120 446 152

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_attributes 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_attributes, and based on these observations, apply Extract Interface, too.

1
<?php if ( !defined( 'ABSPATH' ) ) exit;
2
3
/*	Check if file is include. No direct access possible with file url	*/
4
if ( !defined( 'WPSHOP_VERSION' ) ) {
5
	die( __('Access is not allowed by this way', 'wpshop') );
6
}
7
8
/**
9
 * Define the different method to manage attributes
10
 *
11
 *	Define the different method and variable used to manage attributes
12
 * @author Eoxia <[email protected]>
13
 * @version 1.0
14
 * @package wpshop
15
 * @subpackage librairies
16
 */
17
18
/**
19
 * Define the different method to manage attributes
20
 * @package wpshop
21
 * @subpackage librairies
22
 */
23
class wpshop_attributes{
24
	/*	Define the database table used in the current class	*/
25
	const dbTable = WPSHOP_DBT_ATTRIBUTE;
26
	/*	Define the url listing slug used in the current class	*/
27
	const urlSlugListing = WPSHOP_URL_SLUG_ATTRIBUTE_LISTING;
28
	/*	Define the url edition slug used in the current class	*/
29
	const urlSlugEdition = WPSHOP_URL_SLUG_ATTRIBUTE_LISTING;
30
	/*	Define the current entity code	*/
31
	const currentPageCode = 'attributes';
32
	/*	Define the page title	*/
33
	const pageContentTitle = 'Attributes';
34
	/*	Define the page title when adding an attribute	*/
35
	const pageAddingTitle = 'Add an attribute';
36
	/*	Define the page title when editing an attribute	*/
37
	const pageEditingTitle = 'Attribute "%s" edit';
38
	/*	Define the page title when editing an attribute	*/
39
	const pageTitle = 'Attributes list';
40
41
	/*	Define the path to page main icon	*/
42
	public $pageIcon = '';
43
	/*	Define the message to output after an action	*/
44
	public $pageMessage = '';
45
46
	public static $select_option_info_cache = array();
47
48
	/**
49
	 *	Get the url listing slug of the current class
50
	 *
51
	 *	@return string The table of the class
52
	 */
53
	function setMessage($message){
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...
54
		$this->pageMessage = $message;
55
	}
56
	/**
57
	 *	Get the url listing slug of the current class
58
	 *
59
	 *	@return string The table of the class
60
	 */
61
	function getListingSlug(){
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...
62
		return self::urlSlugListing;
63
	}
64
	/**
65
	 *	Get the url edition slug of the current class
66
	 *
67
	 *	@return string The table of the class
68
	 */
69
	function getEditionSlug(){
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...
70
		return self::urlSlugEdition;
71
	}
72
	/**
73
	 *	Get the database table of the current class
74
	 *
75
	 *	@return string The table of the class
76
	 */
77
	public static function getDbTable(){
78
		return self::dbTable;
79
	}
80
	/**
81
	 *	Define the title of the page
82
	 *
83
	 *	@return string $title The title of the page looking at the environnement
84
	 */
85
	function pageTitle(){
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...
86
		$action = isset($_REQUEST['action']) ? sanitize_text_field($_REQUEST['action']) : '';
87
		$objectInEdition = isset($_REQUEST['id']) ? sanitize_key($_REQUEST['id']) : '';
88
		$page = !empty( $_GET['page'] ) ? sanitize_text_field( $_GET['page'] ) : '';
89
90
		$title = __(self::pageTitle, 'wpshop' );
91
		if($action != ''){
92 View Code Duplication
			if(($action == 'edit') || ($action == 'delete')){
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...
93
				$editedItem = self::getElement($objectInEdition);
94
				$title = sprintf(__(self::pageEditingTitle, 'wpshop'), str_replace("\\", "", $editedItem->frontend_label));
95
			}
96
			elseif($action == 'add')
97
				$title = __(self::pageAddingTitle, 'wpshop');
98
		}
99
		elseif((self::getEditionSlug() != self::getListingSlug()) && ($page == self::getEditionSlug()))
100
			$title = __(self::pageAddingTitle, 'wpshop');
101
102
		return $title;
103
	}
104
105
	/**
106
	 *	Define the different message and action after an action is send through the element interface
107
	 */
108
	function elementAction(){
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...
109
		global $wpdb, $initialEavData;
110
111
		$pageMessage = $actionResult = '';
112
		$attribute_undeletable = unserialize(WPSHOP_ATTRIBUTE_UNDELETABLE);
113
114
		/*	Start definition of output message when action is doing on another page	*/
115
		/************		CHANGE THE FIELD NAME TO TAKE TO DISPLAY				*************/
116
		/****************************************************************************/
117
		$action = isset($_REQUEST['action']) ? sanitize_text_field($_REQUEST['action']) : 'add';
118
		$saveditem = isset($_REQUEST['saveditem']) ? sanitize_text_field($_REQUEST['saveditem']) : '';
119
		$set_section = !empty($_REQUEST[self::getDbTable()]['set_section']) ? sanitize_text_field($_REQUEST[self::getDbTable()]['set_section']) : '';
120
		//@TODO $_REQUEST
121
		$id = !empty($_REQUEST['id']) ? (int) $_REQUEST['id'] : null;
122
		if(!empty($action) && ($action=='activate') ){
123
			if( isset($id) ) {
124
				$query = $wpdb->update(self::getDbTable(), array('status'=>'moderated'), array('id'=>$id));
0 ignored issues
show
Unused Code introduced by
$query 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...
125
				wpshop_tools::wpshop_safe_redirect(admin_url('admin.php?page=' . self::getListingSlug() . "&action=edit&id=" . $id));
126
			}
127
		}
128 View Code Duplication
		if(($action != '') && ($action == 'saveok') && ($saveditem > 0)){
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...
129
			$editedElement = self::getElement($saveditem);
130
			$pageMessage = '<img src="' . WPSHOP_SUCCES_ICON . '" alt="action success" class="wpshopPageMessage_Icon" />' . sprintf(__('%s succesfully saved', 'wpshop'), '<span class="bold" >' . $editedElement->code . '</span>');
131
		}
132
		elseif(($action != '') && ($action == 'deleteok') && ($saveditem > 0)){
133
			$editedElement = self::getElement($saveditem, "'deleted'");
134
			$pageMessage = '<img src="' . WPSHOP_SUCCES_ICON . '" alt="action success" class="wpshopPageMessage_Icon" />' . sprintf(__('%s succesfully deleted', 'wpshop'), '<span class="bold" >' . $editedElement->code . '</span>');
135
		}
136
137
		$attribute_parameter = !empty( $_REQUEST[self::getDbTable()] ) ? (array)$_REQUEST[self::getDbTable()] : array();
138
		 if ( !empty($set_section) ) unset($attribute_parameter['set_section']);
139
140
		$wpshop_attribute_combo_values_list_order_def = !empty($attribute_parameter['wpshop_attribute_combo_values_list_order_def']) ? $attribute_parameter['wpshop_attribute_combo_values_list_order_def'] : array();
141
		// @TODO $_REQUEST
142
		// unset($_REQUEST[self::getDbTable()]['wpshop_attribute_combo_values_list_order_def']);
0 ignored issues
show
Unused Code Comprehensibility introduced by
88% 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...
143
144
		if(!isset($attribute_parameter['status'])){
145
			$attribute_parameter['status'] = 'moderated';
146
		}
147
		if(!isset($attribute_parameter['is_historisable'])){
148
			$attribute_parameter['is_historisable'] = 'no';
149
		}
150
		if(!isset($attribute_parameter['is_required'])){
151
			$attribute_parameter['is_required'] = 'no';
152
		}
153
		if(!isset($attribute_parameter['is_used_in_admin_listing_column'])){
154
			$attribute_parameter['is_used_in_admin_listing_column'] = 'no';
155
		}
156
		if(!isset($attribute_parameter['is_used_in_quick_add_form'])){
157
			$attribute_parameter['is_used_in_quick_add_form'] = 'no';
158
		}
159
		if(!isset($attribute_parameter['is_intrinsic'])){
160
			$attribute_parameter['is_intrinsic'] = 'no';
161
		}
162
		if(!isset($attribute_parameter['is_requiring_unit'])){
163
			$attribute_parameter['is_requiring_unit'] = 'no';
164
		}
165
		if(!isset($attribute_parameter['is_visible_in_front'])){
166
			$attribute_parameter['is_visible_in_front'] = 'no';
167
		}
168
		if(!isset($attribute_parameter['is_visible_in_front_listing'])){
169
			$attribute_parameter['is_visible_in_front_listing'] = 'no';
170
		}
171
		if(!isset($attribute_parameter['is_used_for_sort_by'])){
172
			$attribute_parameter['is_used_for_sort_by'] = 'no';
173
		}
174
		if(!isset($attribute_parameter['is_visible_in_advanced_search'])){
175
			$attribute_parameter['is_visible_in_advanced_search'] = 'no';
176
		}
177
		if(!isset($attribute_parameter['is_searchable'])){
178
			$attribute_parameter['is_searchable'] = 'no';
179
		}
180
		if(!isset($attribute_parameter['is_used_for_variation'])){
181
			$attribute_parameter['is_used_for_variation'] = 'no';
182
		}
183
		if(!isset($attribute_parameter['is_used_in_variation'])){
184
			$attribute_parameter['is_used_in_variation'] = 'no';
185
		}
186
		if(!isset($attribute_parameter['is_user_defined'])){
187
			$attribute_parameter['is_user_defined'] = 'no';
188
		}
189
		if(!isset($attribute_parameter['_display_informations_about_value'])){
190
			$attribute_parameter['_display_informations_about_value'] = 'no';
191
		}
192
193
		/*	Check frontend input and data type	*/
194
		if (!empty($attribute_parameter['frontend_input'])) {
195
			switch ($attribute_parameter['frontend_input']) {
196 View Code Duplication
				case 'short_text':
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...
197
						$attribute_parameter['frontend_input'] = 'text';
198
						if ( empty($attribute_parameter['backend_input']) ) $attribute_parameter['backend_input'] = 'text';
199
						$attribute_parameter['data_type'] = 'varchar';
200
					break;
201 View Code Duplication
				case 'date_field':
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...
202
						$attribute_parameter['frontend_input'] = 'text';
203
						if ( empty($attribute_parameter['backend_input']) ) $attribute_parameter['backend_input'] = 'text';
204
						$attribute_parameter['data_type'] = 'datetime';
205
					break;
206 View Code Duplication
				case 'float_field':
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...
207
						$attribute_parameter['frontend_input'] = 'text';
208
						if ( empty($attribute_parameter['backend_input']) ) $attribute_parameter['backend_input'] = 'text';
209
						$attribute_parameter['data_type'] = 'decimal';
210
					break;
211 View Code Duplication
				case 'hidden_field':
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...
212
						$attribute_parameter['frontend_input'] = 'hidden';
213
						if ( empty($attribute_parameter['backend_input']) ) $attribute_parameter['backend_input'] = 'text';
214
						$attribute_parameter['data_type'] = 'varchar';
215
					break;
216 View Code Duplication
				case 'pass_field':
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...
217
						$attribute_parameter['frontend_input'] = 'password';
218
						if ( empty($attribute_parameter['backend_input']) ) $attribute_parameter['backend_input'] = 'text';
219
						$attribute_parameter['data_type'] = 'varchar';
220
					break;
221
222 View Code Duplication
				case 'select':
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...
223
						$attribute_parameter['frontend_input'] = 'select';
224
						if ( empty($attribute_parameter['backend_input']) || empty($id) )
225
							$attribute_parameter['backend_input'] = 'multiple-select';
226
						$attribute_parameter['data_type'] = 'integer';
227
					break;
228 View Code Duplication
				case 'multiple-select':
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...
229
						$attribute_parameter['frontend_input'] = 'multiple-select';
230
						if ( empty($attribute_parameter['backend_input']) || empty($id) )
231
							$attribute_parameter['backend_input'] = 'multiple-select';
232
						$attribute_parameter['data_type'] = 'integer';
233
					break;
234 View Code Duplication
				case 'radio':
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...
235
						$attribute_parameter['frontend_input'] = 'radio';
236
						if ( empty($attribute_parameter['backend_input']) || empty($id) )
237
							$attribute_parameter['backend_input'] = 'multiple-select';
238
						$attribute_parameter['data_type'] = 'integer';
239
					break;
240 View Code Duplication
				case 'checkbox':
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...
241
						$attribute_parameter['frontend_input'] = 'checkbox';
242
						if ( empty($attribute_parameter['backend_input']) || empty($id) )
243
							$attribute_parameter['backend_input'] = 'multiple-select';
244
						$attribute_parameter['data_type'] = 'integer';
245
					break;
246
247 View Code Duplication
				case 'textarea':
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...
248
						$attribute_parameter['frontend_input'] = 'textarea';
249
						if ( empty($attribute_parameter['backend_input']) || empty($id) )
250
							$attribute_parameter['backend_input'] = 'textarea';
251
						$attribute_parameter['data_type'] = 'text';
252
					break;
253
			}
254
		}
255
		else {
256
			$attribute_parameter['frontend_input'] = 'text';
257
			if ( empty($attribute_parameter['backend_input']) ) $attribute_parameter['backend_input'] = 'text';
258
			$attribute_parameter['data_type'] = 'varchar';
259
		}
260
261
		/*	Check if the checkbox for ajax activation is checked for data update	*/
262
		// if(!isset($attribute_parameter['use_ajax_for_filling_field']) || empty($attribute_parameter['use_ajax_for_filling_field'])){
0 ignored issues
show
Unused Code Comprehensibility introduced by
87% 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...
263
			// $attribute_parameter['use_ajax_for_filling_field']='no';
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
264
		// }
265
		$attribute_parameter['use_ajax_for_filling_field'] = 'yes';
266
		if( $attribute_parameter['backend_input'] == 'multiple-select' ) {
267
			$attribute_parameter['is_used_for_variation'] = 'yes';
268
		}
269
270
		/*	Define the database operation type from action launched by the user	 */
271
		$attribute_parameter['default_value'] = (!empty($attribute_parameter['default_value']) && is_array($attribute_parameter['default_value'])) ? serialize($attribute_parameter['default_value']) : (isset($attribute_parameter['default_value']) ? str_replace('"', "'", $attribute_parameter['default_value']) : '');
272
		if ( $attribute_parameter['data_type'] == 'datetime' ) {
273
			$date_default_value_trasform_into_config = array('default_value' => $attribute_parameter['default_value'], 'field_options' => (!empty($_POST[self::getDbTable() . '_options']) ? sanitize_text_field($_POST[self::getDbTable() . '_options']) : null));
274
			$attribute_parameter['default_value'] = serialize( $date_default_value_trasform_into_config );
275
		}
276
		/*****************************		GENERIC				**************************/
277
		/*************************************************************************/
278
		$pageAction = (!empty($attribute_parameter['frontend_label']) && isset($_REQUEST[self::getDbTable() . '_action'])) ? sanitize_text_field($_REQUEST[self::getDbTable() . '_action']) : ((!empty($_GET['action']) && ($_GET['action']=='delete')) ? sanitize_text_field($_GET['action']) : '');
279
		$id = isset($attribute_parameter['id']) ? sanitize_key($attribute_parameter['id']) : ((!empty($_GET['id'])) ? $_GET['id'] : '');
280
		if(($pageAction != '') && (($pageAction == 'edit') || ($pageAction == 'editandcontinue'))){
281
			if(current_user_can('wpshop_edit_attributes')){
282
				$attribute_parameter['last_update_date'] = date('Y-m-d H:i:s');
283
				if($pageAction == 'delete'){
284
					$attribute_code = $attribute_parameter['code'];
285
					if(!isset($attribute_parameter['code']) || ($attribute_parameter['code'] == '')){
286
						$attribute = self::getElement($id, "'valid', 'moderated', 'notused'", 'id');
287
						$attribute_code = $attribute->code;
288
					}
289
					if(!in_array($attribute_code, $attribute_undeletable)){
290
						if(current_user_can('wpshop_delete_attributes')){
291
							$attribute_parameter['status'] = 'deleted';
292
						}
293
						else{
294
							$actionResult = 'userNotAllowedForActionDelete';
0 ignored issues
show
Unused Code introduced by
$actionResult 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...
295
						}
296
					}
297
					else{
298
						$actionResult = 'unDeletableAtribute';
0 ignored issues
show
Unused Code introduced by
$actionResult 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...
299
					}
300
				}
301
				$actionResult = wpshop_database::update($attribute_parameter, $id, self::getDbTable());
302
			}
303
			else{
304
				$actionResult = 'userNotAllowedForActionEdit';
305
			}
306
		}
307
		elseif(($pageAction != '') && (($pageAction == 'delete'))){
308
			$attribute_code = '';
309 View Code Duplication
			if (empty(	$attribute_parameter['code'])) {
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...
310
				$attribute = self::getElement($id, "'valid', 'moderated', 'notused', 'deleted'", 'id');
311
				$attribute_code = $attribute->code;
312
			}
313 View Code Duplication
			if (!in_array($attribute_code, $attribute_undeletable)) {
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...
314
				if(current_user_can('wpshop_delete_attributes')){
315
					$attribute_parameter['last_update_date'] = current_time('mysql', 0);
316
					$attribute_parameter['status'] = 'deleted';
317
					$actionResult = wpshop_database::update($attribute_parameter, $id, self::getDbTable());
318
				}
319
				else
320
					$actionResult = 'userNotAllowedForActionDelete';
321
			}
322
			else
323
				$actionResult = 'unDeletableAtribute';
324
		}
325 View Code Duplication
		elseif(($pageAction != '') && (($pageAction == 'save') || ($pageAction == 'saveandcontinue') || ($pageAction == 'add'))){
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...
326
			if(current_user_can('wpshop_add_attributes')){
327
				$attribute_parameter['creation_date'] = current_time('mysql', 0);
328
				if(trim($attribute_parameter['code']) == ''){
329
					$attribute_parameter['code'] = $attribute_parameter['frontend_label'];
330
				}
331
				$attribute_parameter['code'] = wpshop_tools::slugify(str_replace("\'", "_", str_replace('\"', "_", $attribute_parameter['code'])), array('noAccent', 'noSpaces', 'lowerCase', 'noPunctuation'));
332
				$code_exists = self::getElement($attribute_parameter['code'], "'valid', 'moderated', 'deleted'", 'code');
333
				if((is_object($code_exists) || is_array($code_exists)) && (count($code_exists) > 0)){
334
					$attribute_parameter['code'] = $attribute_parameter['code'] . '_' . (count($code_exists) + rand());
335
				}
336
				$actionResult = wpshop_database::save($attribute_parameter, self::getDbTable());
337
				$id = $wpdb->insert_id;
338
			}
339
			else{
340
				$actionResult = 'userNotAllowedForActionAdd';
341
			}
342
		}
343
344
		/*	When an action is launched and there is a result message	*/
345
		/************		CHANGE THE FIELD NAME TO TAKE TO DISPLAY				*************/
346
		/************		CHANGE ERROR MESSAGE FOR SPECIFIC CASE					*************/
347
		/****************************************************************************/
348
		if($actionResult != ''){
349
			$elementIdentifierForMessage = __('the attribute', 'wpshop');
350
			if(!empty($attribute_parameter['name']))$elementIdentifierForMessage = '<span class="bold" >' . $attribute_parameter['frontend_label'] . '</span>';
351
			if ($actionResult == 'error') {/*	CHANGE HERE FOR SPECIFIC CASE	*/
352
				$pageMessage .= '<img src="' . WPSHOP_ERROR_ICON . '" alt="action error" class="wpshopPageMessage_Icon" />' . sprintf(__('An error occured while saving %s', 'wpshop'), $elementIdentifierForMessage, ' -> ' . $wpdb->last_error);
353
			}
354
			else if (($actionResult == 'done') || ($actionResult == 'nothingToUpdate')) {/*	CHANGE HERE FOR SPECIFIC CASE	*/
355
				/*****************************************************************************************************************/
356
				/*************************			CHANGE FOR SPECIFIC ACTION FOR CURRENT ELEMENT				****************************/
357
				/*****************************************************************************************************************/
358
				/*	Add the different option for the attribute that are set to combo box for frontend input	*/
359
				$done_options_value = array();
360
				$default_value = $attribute_parameter['default_value'];
361
				$i = 1;
362
				$options = !empty($_REQUEST['options']) ? (array) $_REQUEST['options'] : array();
363
				$optionsValue = !empty($_REQUEST['optionsValue']) ? (array) $_REQUEST['optionsValue'] : array();
364
				$optionsUpdate = !empty($_REQUEST['optionsUpdate']) ? (array) $_REQUEST['optionsUpdate'] : array();
365
				$optionsUpdateValue = !empty($_REQUEST['optionsUpdateValue']) ? (array) $_REQUEST['optionsUpdateValue'] : array();
366
				if ( !empty($optionsUpdate) ) {
367
					/**
368
					 *	Check if there is an attribute code into sended request or if we have to get the code from database (Bug fix)
369
					 */
370 View Code Duplication
					if (empty($attribute_parameter['code'])) {
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...
371
						$attribute = self::getElement($id, "'valid', 'moderated', 'notused'", 'id');
372
						$attribute_code = $attribute->code;
373
					}
374
					else {
375
						$attribute_code = $attribute_parameter['code'];
376
					}
377
					foreach ($optionsUpdate as $option_key => $option_label) {
378
						$option_value = !empty($optionsUpdateValue[$option_key]) ? str_replace(",", ".", $optionsUpdateValue[$option_key]) : '';
379
380
						if ( empty($option_value) || !in_array($option_value, $done_options_value) ) {
381
							/*	Update an existing value only if the value does not exist into existing list	*/
382
							$label = (($option_label != '') ? $option_label : str_replace(",", ".", $option_value));
383
							$value = str_replace(",", ".", $option_value);
384
							if( !WPSHOP_DISPLAY_VALUE_FOR_ATTRIBUTE_SELECT ) {
385
								$label = $option_label;
386
								$value =  str_replace(",", ".", $label);
387
							}
388
389
							$wpdb->update(WPSHOP_DBT_ATTRIBUTE_VALUES_OPTIONS, array('last_update_date' => current_time('mysql', 0), 'position' => $i, 'label' => stripslashes($label), 'value' => stripslashes($value)), array('id' => $option_key));
390
							$done_options_value[] = str_replace(",", ".", $option_value);
391
392
							/*	Check if this value is used for price calculation and make update on the different product using this value	*/
393
							if($attribute_code == WPSHOP_PRODUCT_PRICE_TAX){
394
								$action = wpshop_prices::mass_update_prices();
0 ignored issues
show
Unused Code introduced by
$action 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...
395
							}
396
						}
397
398 View Code Duplication
						if($default_value == $option_key) {
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...
399
							/*	Update an existing a only if the value does not exist into existing list	*/
400
							$wpdb->update(WPSHOP_DBT_ATTRIBUTE, array('last_update_date' => current_time('mysql', 0), 'default_value' => $option_key), array('id' => $id));
401
							$done_options_value[] = str_replace(",", ".", $option_value);
402
						}
403
						$i++;
404
					}
405
				}
406
				if ( !empty($options) ) {
407
					foreach ( $options as $option_key => $option_label ) {
408
						$option_value = !empty($optionsValue[$option_key]) ? str_replace(",", ".", $optionsValue[$option_key]) : sanitize_title($option_label);
409
410
						/*	Check what value to use for the new values	*/
411
						$label = (!empty($option_label) ? $option_label : str_replace(",", ".", $option_value));
412
						if( !WPSHOP_DISPLAY_VALUE_FOR_ATTRIBUTE_SELECT && empty($option_value) ) {
413
							$label = $option_label;
414
							$option_value = sanitize_title($label);
415
						}
416
417
						// If the optionsUpdateValue is empty, set it a empty array to avoid error calling the in_array() function
418
						// $_REQUEST['optionsUpdateValue'] = !empty($_REQUEST['optionsUpdateValue']) ? $_REQUEST['optionsUpdateValue'] : array();
0 ignored issues
show
Unused Code Comprehensibility introduced by
74% 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...
419
420
						if (!in_array($option_value, $done_options_value) && !in_array($option_value, $optionsUpdateValue) ) {
421
422
							$wpdb->insert(WPSHOP_DBT_ATTRIBUTE_VALUES_OPTIONS, array('creation_date' => current_time('mysql', 0), 'status' => 'valid', 'attribute_id' => $id, 'position' => $i, 'label' => stripslashes($label), 'value' => stripslashes($option_value)));
423
							$done_options_value[] = str_replace(",", ".", $option_value);
424
							$last_insert_id = $wpdb->insert_id;
425
426 View Code Duplication
							if (empty($default_value)) {
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...
427
								/*	Update an existing a only if the value does not exist into existing list	*/
428
								$wpdb->update(WPSHOP_DBT_ATTRIBUTE, array('last_update_date' => current_time('mysql', 0), 'default_value' => $last_insert_id), array('id' => $id));
429
								$done_options_value[] = str_replace(",", ".", $option_value);
430
							}
431
432
						}
433
						$i++;
434
					}
435
				}
436
437
				// If the is_used_for_sort_by is mark as yes, we have to get out some attributes and save it separately
438
				if( (!empty($attribute_parameter['is_used_for_sort_by']) && ($attribute_parameter['is_used_for_sort_by'] == 'yes')) || (!empty($attribute_parameter['is_filterable']) && ($attribute_parameter['is_filterable'] == 'yes')) || (!empty($attribute_parameter['is_searchable']) && ($attribute_parameter['is_searchable'] == 'yes')) ){
439
					$attribute_code = $attribute_parameter['code'];
440
					if(!isset($attribute_parameter['code']) || ($attribute_parameter['code'] == '')){
441
						$attribute = self::getElement($id, "'valid', 'moderated', 'notused'", 'id');
442
						$attribute_code = $attribute->code;
443
					}
444
445
					$count_products = wp_count_posts(WPSHOP_NEWTYPE_IDENTIFIER_PRODUCT);
446
					for( $i = 0; $i <= $count_products->publish; $i+= 20 ) {
447
						$query = $wpdb->prepare( 'SELECT * FROM '. $wpdb->posts .' WHERE post_type = %s AND post_status = %s ORDER BY ID DESC LIMIT '.$i.', 20', WPSHOP_NEWTYPE_IDENTIFIER_PRODUCT, 'publish' );
448
						$products = $wpdb->get_results( $query );
449
						if ( !empty($products) ) {
450
							foreach( $products as $product ) {
451
								$query = $wpdb->prepare("SELECT value FROM " . WPSHOP_DBT_ATTRIBUTE_VALUES_PREFIX . $attribute_parameter['data_type'] . " WHERE attribute_id = %d AND entity_type_id = %d AND entity_id = %d AND value != '' ORDER BY creation_date_value DESC", $id, $attribute_parameter['entity_id'], $product->ID);
452
								$value = $wpdb->get_var($query);
453
								update_post_meta($product->ID, '_' . $attribute_code, $value);
454
							}
455
						}
456
					}
457
					wp_reset_query();
458
				}
459
460
				if ( $pageAction != 'delete' ) {/*	Add the new attribute in the additionnal informations attribute group	*/
461
					if ( !empty($set_section) ) {
462
						$choosen_set_section = explode('_', $set_section);
463
						$set_id = $choosen_set_section[0];
464
						$group_id = $choosen_set_section[1];
465
					}
466
					else{
467
						$attribute_current_attribute_set = 0;
0 ignored issues
show
Unused Code introduced by
$attribute_current_attribute_set 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...
468
						$query = $wpdb->prepare("
469
								SELECT id
470
								FROM " . WPSHOP_DBT_ATTRIBUTE_DETAILS . " AS ATTRIBUTE_SET_DETAILS
471
								WHERE ATTRIBUTE_SET_DETAILS.status = 'valid'
472
									AND ATTRIBUTE_SET_DETAILS.attribute_id = %d
473
									AND ATTRIBUTE_SET_DETAILS.entity_type_id = %d", $id, $attribute_parameter['entity_id']);
474
						$attribute_current_attribute_set = $wpdb->get_results($query);
475
476
						if ( empty($attribute_current_attribute_set) ) {
477
							$query = $wpdb->prepare("
478
								SELECT
479
									(
480
										SELECT ATTRIBUTE_SET.id
481
										FROM " . WPSHOP_DBT_ATTRIBUTE_SET . " AS ATTRIBUTE_SET
482
										WHERE ATTRIBUTE_SET.entity_id = %d
483
											AND ATTRIBUTE_SET.default_set = 'yes'
484
									) AS attribute_set_id,
485
									(
486
										SELECT ATTRIBUTE_GROUP.id
487
										FROM " . WPSHOP_DBT_ATTRIBUTE_GROUP . " AS ATTRIBUTE_GROUP
488
										INNER JOIN " . WPSHOP_DBT_ATTRIBUTE_SET . " AS ATTRIBUTE_SET ON ((ATTRIBUTE_SET.id = ATTRIBUTE_GROUP.attribute_set_id) AND (ATTRIBUTE_SET.entity_id = %d))
489
										WHERE ATTRIBUTE_GROUP.default_group = 'yes'
490
											AND ATTRIBUTE_GROUP.status = 'valid'
491
									) AS attribute_group_id"
492
								, $attribute_parameter['entity_id'], $attribute_parameter['entity_id'], $attribute_parameter['entity_id'], $attribute_parameter['entity_id']
493
							);
494
							$wpshop_default_group = $wpdb->get_row($query);
495
496
							$set_id = $wpshop_default_group->attribute_set_id;
497
							$default_group_id = ( !empty( $wpshop_default_group->default_attribute_group_id) ) ? $wpshop_default_group->default_attribute_group_id : '';
498
							$group_id = !empty($default_group_id) ? $default_group_id : $wpshop_default_group->attribute_group_id;
499
						}
500
					}
501
502
					if ( !empty($set_id) && !empty($group_id) ) {
503
						$query = $wpdb->prepare(
504
								"SELECT (MAX(position) + 1) AS position
505
								FROM " . WPSHOP_DBT_ATTRIBUTE_DETAILS . "
506
								WHERE attribute_set_id = %s
507
								AND attribute_group_id = %s
508
								AND entity_type_id = %s ",
509
								$set_id,
510
								$group_id,
511
								$attribute_parameter['entity_id']
512
						);
513
						$wpshopAttributePosition = $wpdb->get_var($query);
514
						if($wpshopAttributePosition == 0)$wpshopAttributePosition = 1;
515
						$wpdb->insert(WPSHOP_DBT_ATTRIBUTE_DETAILS, array('status' => 'valid', 'creation_date' => current_time('mysql', 0), 'entity_type_id' => $attribute_parameter['entity_id'], 'attribute_set_id' => $set_id, 'attribute_group_id' => $group_id, 'attribute_id' => $id, 'position' => $wpshopAttributePosition));
516
					}
517
				}
518
519
				if ( !empty($wpshop_attribute_combo_values_list_order_def) ) {
520
					$post_order = explode(',', $wpshop_attribute_combo_values_list_order_def);
521
					$position = 1;
522
					foreach ($post_order as $post_id) {
523
						$wpdb->update($wpdb->posts, array('menu_order' => $position), array('ID' => str_replace('post_', '', $post_id)));
524
						$position++;
525
					}
526
				}
527
528
				/*************************			GENERIC    ****************************/
529
				/*************************************************************************/
530
				$pageMessage .= '<img src="' . WPSHOP_SUCCES_ICON . '" alt="action success" class="wpshopPageMessage_Icon" />' . sprintf(__('%s succesfully saved', 'wpshop'), $elementIdentifierForMessage);
531
				/* if(($pageAction == 'edit') || ($pageAction == 'save')){
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% 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...
532
					wpshop_tools::wpshop_safe_redirect(admin_url('admin.php?page=' . self::getListingSlug() . "&action=saveok&saveditem=" . $id));
533
				}
534
				else */
535 View Code Duplication
				if ( $pageAction == 'add' )
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...
536
					wpshop_tools::wpshop_safe_redirect(admin_url('admin.php?page=' . self::getListingSlug() . "&action=edit&id=" . $id));
537
				elseif ( $pageAction == 'delete' )
538
					wpshop_tools::wpshop_safe_redirect(admin_url('admin.php?page=' . self::getListingSlug() . "&action=deleteok&saveditem=" . $id));
539
			}
540 View Code Duplication
			elseif(($actionResult == 'userNotAllowedForActionEdit') || ($actionResult == 'userNotAllowedForActionAdd') || ($actionResult == 'userNotAllowedForActionDelete')){
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...
541
				$pageMessage .= '<img src="' . WPSHOP_ERROR_ICON . '" alt="action error" class="wpshopPageMessage_Icon" />' . __('You are not allowed to do this action', 'wpshop');
542
			}
543
			elseif(($actionResult == 'unDeletableAtribute')){
544
				$pageMessage .= '<img src="' . WPSHOP_ERROR_ICON . '" alt="action error" class="wpshopPageMessage_Icon" />' . __('This attribute could not be deleted due to configuration', 'wpshop');
545
			}
546
547
			if(empty($attribute_parameter['frontend_label']) && ($pageAction!='delete')){
548
				$pageMessage .= __('Please enter an label for the attribut', 'wpshop');
549
			}
550
		}
551
552
		self::setMessage($pageMessage);
553
	}
554
555
	/**
556
	 *	Return the list page content, containing the table that present the item list
557
	 *
558
	 *	@return string $listItemOutput The html code that output the item list
559
	 */
560
	function elementList() {
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...
561
		global $wpdb;
562
		//Create an instance of our package class...
563
		$wpshop_list_table = new wpshop_attributes_custom_List_table();
564
		//Fetch, prepare, sort, and filter our data...
565
		$status="'valid'";
566
		$attribute_status = !empty($_REQUEST['attribute_status']) ? sanitize_text_field( $_REQUEST['attribute_status'] ) : null;
567
		$s = !empty($_REQUEST['s']) ? sanitize_text_field( $_REQUEST['s'] ) : null;
568
		$order = !empty($_REQUEST['order']) ? sanitize_text_field($_REQUEST['order']) : null;
569
		$orderby = !empty($_REQUEST['orderby']) ? sanitize_text_field($_REQUEST['orderby']) : null;
0 ignored issues
show
Unused Code introduced by
$orderby 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...
570
		if(!empty($attribute_status)){
571
			switch($attribute_status){
572
				case 'unactive':
573
					$status="'moderated', 'notused'";
574
					if(empty($order_by) && empty($order)){
0 ignored issues
show
Bug introduced by
The variable $order_by does not exist. Did you mean $orderby?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
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...
575
						// @TODO : REQUEST
576
						// $_REQUEST['orderby']='status';
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
577
						// $_REQUEST['order']='asc';
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
578
					}
579
					break;
580
				default:
581
					$status="'".sanitize_text_field($_REQUEST['attribute_status'])."'";
582
					break;
583
			}
584
		}
585 View Code Duplication
		if ( !empty($s) ) {
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...
586
			$query = $wpdb->prepare("SELECT * FROM " . self::dbTable . ' WHERE frontend_label LIKE "%%%1$s%%" OR frontend_label LIKE "%%%2$s%%" AND backend_label LIKE "%%%1$s%%" OR backend_label LIKE "%%%2$s%%" AND code LIKE "%%%1$s%%" OR code LIKE "%%%2$s%%"', $s, __($s, 'wpshop') );
587
			$attr_set_list = $wpdb->get_results( $query );
588
		}
589
		else {
590
			$attr_set_list = self::getElement( '', $status );
591
		}
592
		$i=0;
593
		$attribute_set_list=array();
594
		foreach($attr_set_list as $attr_set){
595
			if(!empty($attr_set->id) && ($attr_set->code != 'product_attribute_set_id') ){
596
				$attribute_set_list[$i]['id'] = $attr_set->id;
597
				$attribute_set_list[$i]['name'] = $attr_set->frontend_label;
598
				$attribute_set_list[$i]['status'] = $attr_set->status;
599
				$attribute_set_list[$i]['entity'] = $attr_set->entity_id;
600
				$attribute_set_list[$i]['code'] = $attr_set->code;
601
				$i++;
602
			}
603
		}
604
605
606
		$wpshop_list_table->datas = $attribute_set_list;
607
		$wpshop_list_table->prepare_items();
608
609
		ob_start();
610
		?>
611
<div class="wrap">
612
	<!-- Forms are NOT created automatically, so you need to wrap the table in one to use features like bulk actions -->
613
	<?php $wpshop_list_table->views() ?>
614
	<form id="attributes_filter" method="get">
615
	    <input type="hidden" name="page" value="<?php echo esc_attr($_REQUEST['page']); ?>" />
616
		<?php $wpshop_list_table->search_box('search', sanitize_text_field($_REQUEST['page']) . '_search_input'); ?>
617
	</form>
618
	<form id="attributes_filter" method="get">
619
		<!-- For plugins, we also need to ensure that the form posts back to our current page -->
620
		<input type="hidden" name="page" value="<?php echo esc_attr($_REQUEST['page']); ?>" />
621
		<!-- Now we can render the completed list table -->
622
		<?php $wpshop_list_table->display() ?>
623
	</form>
624
</div>
625
<?php
626
$element_output = ob_get_contents();
627
ob_end_clean();
628
629
		return $element_output;
630
	}
631
632
	/**
633
	 *	Return the page content to add a new item
634
	 *
635
	 *	@return string The html code that output the interface for adding a nem item
636
	 */
637
	function elementEdition($itemToEdit = '') {
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...
638
		ini_set('display_errors', true);
639
		error_reporting(E_ALL);
640
		global $attribute_displayed_field, $attribute_options_group;
641
		$dbFieldList = wpshop_database::fields_to_input(self::getDbTable());
642
		$editedItem = '';
643
		if($itemToEdit != '')
644
			$editedItem = self::getElement($itemToEdit);
645
646
		$the_form_content_hidden = $the_form_general_content = '';
647
		$the_form_option_content_list = array();
648
		foreach($dbFieldList as $input_key => $input_def){
649
650
			if(!isset($attribute_displayed_field) || !is_array($attribute_displayed_field) || in_array($input_def['name'], $attribute_displayed_field)){
651
				$input_def['label'] = $input_def['name'];
652
				$input_def_id=$input_def['id']='wpshop_' . self::currentPageCode . '_edition_table_field_id_'.$input_def['label'];
653
654
				$pageAction = isset($_REQUEST[self::getDbTable() . '_action']) ? sanitize_text_field($_REQUEST[self::getDbTable() . '_action']) : '';
655
				$requestFormValue = isset($_REQUEST[self::currentPageCode][$input_def['label']]) ? sanitize_text_field($_REQUEST[self::currentPageCode][$input_def['label']]) : '';
656
				$currentFieldValue = $input_def['value'];
657 View Code Duplication
				if(is_object($editedItem))
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...
658
					$currentFieldValue = $editedItem->{$input_def['label']};
659
				elseif(($pageAction != '') && ($requestFormValue != ''))
660
					$currentFieldValue = $requestFormValue;
661
662
				if($input_def['label'] == 'status'){
663 View Code Duplication
					if(in_array('notused', $input_def['possible_value'])){
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...
664
						$key = array_keys($input_def['possible_value'], 'notused');
665
						unset($input_def['possible_value'][$key[0]]);
666
					}
667 View Code Duplication
					if(in_array('dbl', $input_def['possible_value'])){
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...
668
						$key = array_keys($input_def['possible_value'], 'dbl');
669
						unset($input_def['possible_value'][$key[0]]);
670
					}
671
672
					$input_def['type'] = 'checkbox';
673
					$input_def['label'] = __('Use this attribute', 'wpshop');
674
					$input_def['possible_value'] = array('valid');
675
					$input_def_id.='_valid';
676
					$input_def['options_label']['custom'] = '<a href="#" title="'.__('Check this box for using this attribute', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
677
				}
678
679
				if ( (substr($input_def['label'], 0, 3) == 'is_') || ( $input_def['label'] == '_display_informations_about_value') ) {
680
					$input_def['type'] = 'checkbox';
681
					$input_def['possible_value'] = 'yes';
682
				}
683
				switch($input_def['label']){
684 View Code Duplication
					case 'is_requiring_unit':
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...
685
						$input_def['options_label']['custom'] = '<a href="#" title="'.__('Check this box for using unit with this attribute', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
686
					break;
687 View Code Duplication
					case 'is_visible_in_front':
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...
688
						$input_def['options_label']['custom'] = '<a href="#" title="'.__('Check this box for displaying this attribute in shop', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
689
					break;
690 View Code Duplication
					case 'is_visible_in_front_listing':
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...
691
						$input_def['options_label']['custom'] = '<a href="#" title="'.__('Check this box for displaying this attribute in product listing in shop', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
692
					break;
693 View Code Duplication
					case 'is_used_for_sort_by':
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...
694
						$input_def['options_label']['custom'] = '<a href="#" title="'.__('Check this box for displaying this attribute into sortbar', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
695
					break;
696 View Code Duplication
					case 'is_searchable':
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...
697
						$input_def['options_label']['custom'] = '<a href="#" title="'.__('Check this box for including values of this attribute as search parameter', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
698
					break;
699 View Code Duplication
					case 'is_visible_in_advanced_search':
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...
700
						$input_def['options_label']['custom'] = '<a href="#" title="'.__('Check this box for using in advanced search form', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
701
					break;
702 View Code Duplication
					case 'frontend_css_class':
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...
703
						$input_def['options_label']['custom'] = '<a href="#" title="'.__('Separate with a space each CSS Class', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
704
					break;
705 View Code Duplication
					case 'backend_css_class':
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...
706
						$input_def['options_label']['custom'] = '<a href="#" title="'.__('Separate with a space each CSS Class', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
707
					break;
708 View Code Duplication
					case 'is_historisable':
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...
709
						$input_def['options_label']['custom'] = '<a href="#" title="'.__('Check this box if you want to save the different value this attribute, each time it is modified', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
710
					break;
711 View Code Duplication
					case 'is_filterable':
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...
712
						$input_def['options_label']['custom'] = '<a href="#" title="'.__('Check this box if you want to use this attribute in the filter search', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
713
					break;
714 View Code Duplication
					case 'is_intrinsic':
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...
715
						$input_def['options_label']['custom'] = '<a href="#" title="'.__('Check this box if this attribute is intrinsic for a product', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
716
					break;
717 View Code Duplication
					case 'is_used_for_variation':
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...
718
						$input_def['options_label']['custom'] = '<a href="#" title="'.__('Check this box if this attribute is used for variation. It means that the user would be able to choose a value in frontend', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
719
					break;
720
					case 'is_used_in_variation':
721
						$input_def['options_label']['custom'] = '<a href="#" title="'.__('Check this box if you want to use this attribute for variation definition', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
722
						if ( !empty($editedItem) && ($editedItem->is_used_for_variation == 'yes') ) {
723
							$input_def['option'] = 'disabled="disabled"';
724
						}
725
					break;
726 View Code Duplication
					case 'is_user_defined':
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...
727
						$input_def['options_label']['custom'] = '<a href="#" title="'.__('Check this box if you want your customer to choose a value for this attribute into frontend product', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
728
					break;
729
				}
730
731
				$input_def['value'] = $currentFieldValue;
732
				if($input_def['label'] == 'code')
733
					$input_def['type'] = 'hidden';
734
				elseif($input_def['label'] == 'entity_id'){
735
					$input_def['possible_value'] = wpshop_entities::get_entities_list();
736
					$input_def['valueToPut'] = 'index';
737
					$input_def['type'] = 'select';
738
739
					$i=0;
740
					foreach($input_def['possible_value'] as $entity_id => $entity_name) {
741
						if($i <= 0){
742
							$current_entity_id = $entity_id;
743
						}
744
						$i++;
745
					}
746
				}
747
				elseif($input_def['label'] == '_unit_group_id'){
748
					$input_def['possible_value'] = wpshop_attributes_unit::get_unit_group();
749
					$input_def['type'] = 'select';
750
				}
751
				elseif($input_def['label'] == '_default_unit'){
752
					$unit_group_list = wpshop_attributes_unit::get_unit_group();
753
					$input_def['possible_value'] = wpshop_attributes_unit::get_unit_list_for_group(!empty($editedItem->_unit_group_id)?$editedItem->_unit_group_id:(!empty($unit_group_list)?$unit_group_list[0]->id:''));
754
					$input_def['type'] = 'select';
755
				}
756
				elseif ($input_def['label'] == 'backend_input') {
757
					if ( !is_object($editedItem) ) {
758
						$input_def['type'] = 'hidden';
759
					}
760
					else {
761
						$new_possible_value = array();
762 View Code Duplication
						switch ( $editedItem->data_type) {
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...
763
							case 'integer':
764
								$new_possible_value[__('Checkbox', 'wpshop')] = 'checkbox';
765
								$new_possible_value[__('Radio button', 'wpshop')] = 'radio';
766
								$new_possible_value[__('select', 'wpshop')] = 'select';
767
								$new_possible_value[__('multiple-select', 'wpshop')] = 'multiple-select';
768
								break;
769
							case 'varchar':
770
								switch ( $input_def['value'] ) {
771
									case 'hidden':
772
										$new_possible_value[__('Hidden field', 'wpshop')] = 'hidden_field';
773
										break;
774
									case 'password':
775
										$new_possible_value[__('Password field', 'wpshop')] = 'pass_field';
776
										break;
777
									default:
778
										$new_possible_value[__('Text field', 'wpshop')] = 'short_text';
779
										break;
780
								}
781
								break;
782
							case 'text':
783
								$new_possible_value[__('Textarea field', 'wpshop')] = 'textarea';
784
								break;
785
							case 'decimal':
786
								$new_possible_value[__('Number field', 'wpshop')] = 'float_field';
787
								break;
788
							case 'datetime':
789
								$new_possible_value[__('Date field', 'wpshop')] = 'date_field';
790
								break;
791
						}
792
						$input_def['possible_value'] = $new_possible_value;
793
					}
794
				}
795
				elseif ($input_def['label'] == 'frontend_input') {
796
					$new_possible_value = array();
797
798
					if ( is_object($editedItem) ) {
799 View Code Duplication
						switch ( $editedItem->data_type) {
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...
800
							case 'integer':
801
								$new_possible_value[__('Checkbox', 'wpshop')] = 'checkbox';
802
								$new_possible_value[__('Radio button', 'wpshop')] = 'radio';
803
								$new_possible_value[__('select', 'wpshop')] = 'select';
804
								$new_possible_value[__('multiple-select', 'wpshop')] = 'multiple-select';
805
								break;
806
							case 'varchar':
807
									switch ( $input_def['value'] ) {
808
										case 'hidden':
809
											$new_possible_value[__('Hidden field', 'wpshop')] = 'hidden_field';
810
										break;
811
										case 'password':
812
											$new_possible_value[__('Password field', 'wpshop')] = 'pass_field';
813
										break;
814
										default:
815
											$new_possible_value[__('Text field', 'wpshop')] = 'short_text';
816
										break;
817
									}
818
								break;
819
							case 'text':
820
									$new_possible_value[__('Textarea field', 'wpshop')] = 'textarea';
821
								break;
822
							case 'decimal':
823
									$new_possible_value[__('Number field', 'wpshop')] = 'float_field';
824
								break;
825
							case 'datetime':
826
									$new_possible_value[__('Date field', 'wpshop')] = 'date_field';
827
								break;
828
						}
829
					}
830
					else {
831
						$new_possible_value[__('Text field', 'wpshop')] = 'short_text';
832
						$new_possible_value[__('Number field', 'wpshop')] = 'float_field';
833
						$new_possible_value[__('Date field', 'wpshop')] = 'date_field';
834
						$new_possible_value[__('Textarea field', 'wpshop')] = 'textarea';
835
						$new_possible_value[__('Password field', 'wpshop')] = 'pass_field';
836
						$new_possible_value[__('Hidden field', 'wpshop')] = 'hidden_field';
837
						$new_possible_value[__('Checkbox', 'wpshop')] = 'checkbox';
838
						$new_possible_value[__('Radio button', 'wpshop')] = 'radio';
839
						$new_possible_value[__('select', 'wpshop')] = 'select';
840
						$new_possible_value[__('multiple-select', 'wpshop')] = 'multiple-select';
841
					}
842
843
					$input_def['possible_value'] = $new_possible_value;
844
845
					if ( !empty($editedItem->frontend_input) ) {
846
						switch ( $editedItem->frontend_input ) {
847
							case 'text':
848
								switch ( $editedItem->data_type ) {
849
									case 'varchar':
850
										$input_def['value'] = 'short_text';
851
									break;
852
									case 'decimal':
853
										$input_def['value'] = 'float_field';
854
									break;
855
									case 'datetime':
856
										$input_def['value'] = 'date_field';
857
									break;
858
									case 'hidden':
859
										$input_def['value'] = 'hidden_field';
860
									break;
861
									case 'password':
862
										$input_def['value'] = 'pass_field';
863
									break;
864
								}
865
							break;
866
							default:
867
								$input_def['value'] = $editedItem->frontend_input;
868
							break;
869
						}
870
					}
871
				}
872
873
				if(is_object($editedItem) && (($input_def['label'] == 'code') || ($input_def['label'] == 'data_type') || ($input_def['label'] == 'entity_id'))){
874
					// $input_def['type'] = 'hidden';
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...
875
					$input_def['option'] = ' disabled="disabled" ';
876
					$the_form_content_hidden .= '<input type="hidden" name="' . self::getDbTable() . '[' . $input_def['name'] . ']" value="' . $input_def['value'] . '" />';
877
					$input_def['label'] = $input_def['name'];
878
					$input_def['name'] = $input_def['name'] . '_already_defined';
879
				}
880
881
				$input_def['value'] = str_replace("\\", "", $input_def['value']);
882
883
				$the_input = wpshop_form::check_input_type($input_def, self::getDbTable());
884
				if ( $input_def['label'] == 'default_value' ) {
885
					if ( !empty($editedItem->frontend_input) ) {
886
						switch ( $editedItem->frontend_input ) {
887
							case 'text':
888
								$input_def['type'] = 'text';
889
								switch ( $editedItem->data_type ) {
890
									case 'datetime':
891
										$the_input = wpshop_attributes::attribute_type_date_config( unserialize($input_def['value']) );
892
893
										$input_def['label'] = __('Date field configuration','wpshop');
894
									break;
895
									default:
896
										$the_input = wpshop_form::check_input_type($input_def, WPSHOP_DBT_ATTRIBUTE);
897
									break;
898
								}
899
							break;
900
							case 'hidden':
901
									$the_input = '';
902
								break;
903
							case 'password':
904
									$the_input = '';
905
								break;
906
							case 'select':
907
							case 'multiple-select':
908
							case 'radio':
909
							case 'checkbox':
910
								$input_def['label'] = __('Options list for attribute','wpshop') . '
911
<div class="alignright wpshop_change_select_data_type" >
912
	+' . __('Change data type for this attribute', 'wpshop') . '
913
</div>';
914
								$the_input = wpshop_attributes::get_select_options_list($itemToEdit, $editedItem->data_type_to_use);
915
916
								break;
917
							case 'textarea':
918
								$input_def['type'] = 'textarea';
919
								$the_input = wpshop_form::check_input_type($input_def, WPSHOP_DBT_ATTRIBUTE);
920
							break;
921
						}
922
					}
923
					else {
924
						$input_def['type']='text';
925
						$the_input = wpshop_form::check_input_type($input_def, self::getDbTable());
926
					}
927
				}
928
				if( $input_def['label'] == '_unit_group_id') {
929
					$the_input .= '<div id="wpshop_loader_input_group_unit"></div>';
930
					$the_input .= '<a class="button-primary" href="#wpshop_unit_group_list" id="wpshop_attribute_group_unit_manager_opener" data-nonce="' . wp_create_nonce( 'load_unit_interface' ) . '">'.__('Manage group unit', 'wpshop').'</a>';
931
				}
932
933
				if( $input_def['label'] == '_default_unit') {
934
					$the_input .= '<div id="wpshop_loader_input_unit"></div>';
935
					$the_input .= '<a class="button-primary" href="#wpshop_unit_list" id="wpshop_attribute_unit_manager_opener" data-nonce="' . wp_create_nonce( 'load_unit_interface' ) . '">'.__('Manage units', 'wpshop').'</a>';
936
					$the_input .= '<input type="hidden" name="input_wpshop_load_attribute_unit_list" id="input_wpshop_load_attribute_unit_list" value="' . wp_create_nonce("wpshop_load_attribute_unit_list") . '" />';
937
					$the_input .= '<div id="wpshop_attribute_unit_manager" title="' . __('Unit management', 'wpshop') . '" class="wpshopHide" ><div class="loading_picture_container" id="product_chooser_picture" ><img src="' . WPSHOP_LOADING_ICON . '" alt="loading..." /></div></div>';
938
				}
939
940
941
				if($input_def['type'] != 'hidden'){
942
					if ( ($input_def['label'] == 'entity_id') && is_object($editedItem) ) {
943
						$the_input .= '<br/><span class="wpshop_duplicate_attribute" >' . __('Duplicate this attribute to . another entity', 'wpshop') . '</span>';
944
					}
945
					$input = '
946
		<tr class="wpshop_' . self::currentPageCode . '_edition_table_line wpshop_' . self::currentPageCode . '_edition_table_line_'.$input_def['name'].'" >
947
			<td class="wpshop_' . self::currentPageCode . '_edition_table_cell wpshop_' . self::currentPageCode . '_edition_table_field_label wpshop_' . self::currentPageCode . '_edition_table_field_label_'.$input_def['name'].'" ><label for="'.$input_def_id.'" >' . __($input_def['label'], 'wpshop') . '</label></td>
948
			<td class="wpshop_' . self::currentPageCode . '_edition_table_cell wpshop_' . self::currentPageCode . '_edition_table_field_input wpshop_' . self::currentPageCode . '_edition_table_field_input_'.$input_def['name'].'" >' . $the_input . '</td>
949
		</tr>';
950
					if ( (substr($input_def['label'], 0, 3) == 'is_') || (substr($input_def['label'], 0, 1) == '_') || in_array($input_def['label'], unserialize( WPSHOP_ATTRIBUTE_DEF_COLUMN_INTO_OPTIONS )) )
951
						$the_form_option_content_list[$input_def['label']] = $input;
952
					else {
953
						$the_form_general_content .= $input;
954
						if ( ($input_def['label'] == 'frontend_input') && !is_object($editedItem) ) {
955
956
							$the_input = wpshop_attributes_set::get_attribute_set_complete_list($current_entity_id,  self::getDbTable(), self::currentPageCode);
0 ignored issues
show
Bug introduced by
The variable $current_entity_id 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...
957
958
							$input = '
959
		<tr class="wpshop_' . self::currentPageCode . '_edition_table_line wpshop_' . self::currentPageCode . '_edition_table_line_set_section" >
960
			<td class="wpshop_' . self::currentPageCode . '_edition_table_cell wpshop_' . self::currentPageCode . '_edition_table_field_label wpshop_' . self::currentPageCode . '_edition_table_field_label_set_section" ><label for="'.self::currentPageCode.'_set_section" >' . __('Affect this new attribute to the set section', 'wpshop') . '</label></td>
961
			<td class="wpshop_' . self::currentPageCode . '_edition_table_cell wpshop_' . self::currentPageCode . '_edition_table_field_input wpshop_' . self::currentPageCode . '_edition_table_field_input_set_section" >' . $the_input . '</td>
962
		</tr>';
963
							$the_form_general_content .= $input;
964
						}
965
					}
966
				}
967
				else{
968
					$the_form_content_hidden .= '
969
				' . $the_input;
970
				}
971
			}
972
		}
973
974
975
976
977
978
		$section_legend = '';
979
		$section_page_code = self::currentPageCode;
980
		$section_content = $the_form_general_content;
981
982
		ob_start();
983
		include(WPSHOP_TEMPLATES_DIR.'admin/admin_box_section.tpl.php');
984
		$the_form_general_content = ob_get_contents();
985
		ob_end_clean();
986
987
		/** It is attribute TVA, add a button to calcilate price in mass **/
988
		if ( !empty($editedItem) && !empty($editedItem->code) && $editedItem->code == 'tx_tva' ) {
989
			$the_form_general_content .= '<input type="button" data-nonce="' . wp_create_nonce( 'wps_update_products_prices' ) . '" id="wps_update_price_infos" value="' .__('Update all products price', 'wpshop').'" /> <img src="' .WPSHOP_LOADING_ICON. '" alt="" id="update_products_loader" /> <br/>';
990
			$the_form_general_content .= __('If you have updated your VAT rates, save it and update your products price after', 'wpshop' );
991
		}
992
		if (!empty($the_form_option_content_list)) {
993
			$the_form_option_content_section='';
994
			foreach ($attribute_options_group as $group_name => $group_content) {
995
				$section_content = '';
996
				foreach ($group_content as $group_code) {
997
					if (array_key_exists($group_code, $the_form_option_content_list)) {
998
						$section_content .= $the_form_option_content_list[$group_code];
999
						unset($the_form_option_content_list[$group_code]);
1000
					}
1001
				}
1002
				$section_legend = __($group_name,'wpshop');
1003
				$section_page_code = self::currentPageCode;
1004
1005
				ob_start();
1006
				include(WPSHOP_TEMPLATES_DIR.'admin/admin_box_section.tpl.php');
1007
				$the_form_option_content_section .= ob_get_contents();
1008
				ob_end_clean();
1009
			}
1010
1011
			/*	Check there are other attributes to display not in defined group	*/
1012
			if (!empty($the_form_option_content_list)) {
1013
				$section_legend = __('General options','wpshop');
1014
				$section_content = implode('', $the_form_option_content_list);
1015
				$section_page_code = self::currentPageCode;
1016
1017
				ob_start();
1018
				include(WPSHOP_TEMPLATES_DIR.'admin/admin_box_section.tpl.php');
1019
				$the_form_option_content = ob_get_contents();
1020
				ob_end_clean();
1021
1022
				$the_form_option_content .= $the_form_option_content_section;
1023
			}
1024
1025
		}
1026
1027
		/*	Default content for the current page	*/
1028
		$bloc_list[self::currentPageCode]['main_info']['title']=__('Main informations', 'wpshop');
0 ignored issues
show
Coding Style Comprehensibility introduced by
$bloc_list was never initialized. Although not strictly required by PHP, it is generally a good practice to add $bloc_list = 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...
1029
		$bloc_list[self::currentPageCode]['main_info']['content'] = $the_form_general_content;
1030
1031
		$bloc_list[self::currentPageCode]['options']['title']=__('Options', 'wpshop');
1032
		$bloc_list[self::currentPageCode]['options']['content']=$the_form_option_content;
0 ignored issues
show
Bug introduced by
The variable $the_form_option_content 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...
1033
1034
		$action = !empty( $_REQUEST['action'] ) ? sanitize_text_field( $_REQUEST['action' ] ) : '';
1035
		$the_form = '
1036
<form name="' . self::getDbTable() . '_form" id="' . self::getDbTable() . '_form" method="post" action="#" >
1037
	' . wpshop_form::form_input(self::getDbTable() . '_action', self::getDbTable() . '_action', (isset($action) && ($action != '') ? sanitize_text_field($action) : 'save') , 'hidden') . '
1038
	' . wpshop_form::form_input(self::currentPageCode . '_form_has_modification', self::currentPageCode . '_form_has_modification', 'no' , 'hidden') . $the_form_content_hidden . wpshop_display::custom_page_output_builder($bloc_list, WPSHOP_ATTRIBUTE_EDITION_PAGE_LAYOUT) . '
1039
</form>
1040
<div title="' . __('Change data type for selected attribute', 'wpshop') . '" id="wpshop_dialog_change_select_data_type" ><div id="wpshop_dialog_change_select_data_type_container" ></div></div>';
1041
		$input_def['possible_value'] = wpshop_entities::get_entities_list();
0 ignored issues
show
Bug introduced by
The variable $input_def seems to be defined by a foreach iteration on line 648. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
1042
		unset($input_def['possible_value'][$current_entity_id]);
1043
		$input_def['valueToPut'] = 'index';
1044
		$input_def['type'] = 'select';
1045
		$input_def['name'] = 'wpshop_entity_to_duplicate_to';
1046
		$input_def['id'] = 'wpshop_entity_to_duplicate_to';
1047
		$the_form .= '
1048
<div title="' . __('Duplicate attribute to another entity', 'wpshop') . '" id="wpshop_dialog_duplicate_attribute" >
1049
	' . __('Choose an entity to copy the selected attribute to', 'wpshop') . '
1050
	' . wpshop_form::check_input_type($input_def) . '
1051
</div>';
1052
1053
		$the_form .= '
1054
<script type="text/javascript" >
1055
	wpshop(document).ready(function(){
1056
		wpshopMainInterface("'.self::getDbTable().'", "' . __('Are you sure you want to quit this page? You will loose all current modification', 'wpshop') . '", "' . __('Are you sure you want to delete this attributes group?', 'wpshop') . '");
1057
1058
		jQuery("#wpshop_dialog_duplicate_attribute").dialog({
1059
			autoOpen: false,
1060
			width: 500,
1061
			height: 100,
1062
			modal: true,
1063
			dialogClass: "wpshop_uidialog_box",
1064
			resizable: false,
1065
			buttons:{
1066
				"'.__('Duplicate', 'wpshop').'": function(){
1067
					var data = {
1068
						action: "wpshop_duplicate_attribute",
1069
						wpshop_ajax_nonce: "' . wp_create_nonce("wpshop_duplicate_attribute") . '",
1070
						attribute_id: jQuery("#wpshop_attributes_edition_table_field_id_id").val(),
1071
						entity: jQuery("#wpshop_entity_to_duplicate_to").val()
1072
					};
1073
					jQuery.post(ajaxurl, data, function(response) {
1074
						if (response[0]) {
1075
							jQuery("#wpshop_dialog_duplicate_attribute").append(response[1]);
1076
						}
1077
						else {
1078
							alert(response[1]);
1079
						}
1080
					}, "json");
1081
				},
1082
				"'.__('Cancel', 'wpshop').'": function(){
1083
					jQuery(this).dialog("close");
1084
					jQuery(".wpshop_duplicate_attribute_result").remove();
1085
				}
1086
			}
1087
		});
1088
		jQuery(".wpshop_duplicate_attribute").live("click", function(){
1089
			jQuery("#wpshop_dialog_duplicate_attribute").dialog("open");
1090
		});
1091
1092
		jQuery("#wpshop_dialog_change_select_data_type").dialog({
1093
			autoOpen: false,
1094
			width: 800,
1095
			height: 200,
1096
			modal: true,
1097
			dialogClass: "wpshop_uidialog_box",
1098
			resizable: false,
1099
			buttons:{
1100
				"'.__('Change type', 'wpshop').'": function(){
1101
					var delete_entity = false;
1102
					if(jQuery("#delete_entity").is(":checked")){
1103
						var delete_entity = true;
1104
					}
1105
					var delete_items_of_entity = false;
1106
					if(jQuery("#delete_items_of_entity").is(":checked")){
1107
						var delete_items_of_entity = true;
1108
					}
1109
					var data = {
1110
						action: "attribute_select_data_type_change",
1111
						wpshop_ajax_nonce: "' . wp_create_nonce("wpshop_attribute_change_select_data_type_change") . '",
1112
						attribute_id: jQuery("#wpshop_attributes_edition_table_field_id_id").val(),
1113
						internal_data: jQuery("#internal_data").val(),
1114
						data_type: jQuery("#wpshop_attribute_change_data_type_new_type").val(),
1115
						delete_entity: delete_entity,
1116
						delete_items_of_entity: delete_items_of_entity
1117
					};
1118
					jQuery.post(ajaxurl, data, function(response) {
1119
						jQuery(".wpshop_attributes_edition_table_field_input_default_value").html( response );
1120
						jQuery("#wpshop_dialog_change_select_data_type").dialog("close");
1121
					}, "json");
1122
				},
1123
				"'.__('Cancel', 'wpshop').'": function(){
1124
					jQuery(this).dialog("close");
1125
				}
1126
			}
1127
		});
1128
1129
		jQuery(".wpshop_attribute_change_select_data_type_deletion_input").live("click",function() {
1130
			var display = false;
1131
			if (jQuery(".wpshop_attribute_change_select_data_type_deletion_input_item").is(":checked") ) {
1132
				display = true;
1133
			}
1134
			if (jQuery(".wpshop_attribute_change_select_data_type_deletion_input_entity").is(":checked") ) {
1135
				display = true;
1136
			}
1137
			if (display) {
1138
				jQuery(".wpshop_attribute_change_data_type_alert").show();
1139
			}
1140
			else {
1141
				jQuery(".wpshop_attribute_change_data_type_alert").hide();
1142
			}
1143
		});
1144
1145
		jQuery(".wpshop_change_select_data_type").live("click",function(){
1146
			jQuery("#wpshop_dialog_change_select_data_type_container").html(jQuery("#wpshopLoadingPicture").html());
1147
			jQuery("#wpshop_dialog_change_select_data_type").dialog("open");
1148
1149
			var data = {
1150
				action: "attribute_select_data_type",
1151
				current_attribute: jQuery("#wpshop_attributes_edition_table_field_id_id").val(),
1152
				wpshop_ajax_nonce: "' . wp_create_nonce("wpshop_attribute_change_select_data_type") . '"
1153
			};
1154
			jQuery.post(ajaxurl, data, function(response) {
1155
				jQuery("#wpshop_dialog_change_select_data_type_container").html( response );
1156
			}, "json");
1157
1158
		});
1159
		jQuery("#wpshop_attributes_edition_table_field_id__unit_group_id").change(function(){
1160
			change_unit_list();
1161
		});';
1162
1163
		if ( !is_object($editedItem) )  {
1164
			$the_form .= '
1165
		jQuery("#wpshop_attributes_edition_table_field_id_frontend_input").change(function(){
1166
			jQuery(".wpshop_attributes_edition_table_field_input_default_value").html(jQuery("#wpshopLoadingPicture").html());
1167
1168
			var data = {
1169
				action: "attribute_output_type",
1170
				current_type: jQuery(this).val(),
1171
				wpshop_ajax_nonce: "' . wp_create_nonce("wpshop_attribute_output_type_selection") . '"
1172
			};
1173
			jQuery.post(ajaxurl, data, function(response) {
1174
				jQuery(".wpshop_attributes_edition_table_field_input_default_value").html((response[0]));
1175
				jQuery(".wpshop_attributes_edition_table_field_label_default_value label").html((response[1]));
1176
			}, "json");
1177
1178
// 			var data = {
1179
// 				action: "attribute_frontend_input_type",
1180
// 				current_type: jQuery(this).val(),
1181
// 				wpshop_ajax_nonce: "' . wp_create_nonce("wpshop_attribute_frontend_input_type") . '"
1182
// 			};
1183
// 			jQuery.getJSON(ajaxurl, data, function(response) {
1184
// 				jQuery("#wpshop_attributes_edition_table_field_id_frontend_input").html(response);
1185
// 			});
1186
1187
		});';
1188
		}
1189
1190
		$the_form .= '
1191
			jQuery("#wpshop_attributes_edition_table_field_id_entity_id").change(function(){
1192
			jQuery(".wpshop_attributes_edition_table_field_input_set_section").html(jQuery("#wpshopLoadingPicture").html());
1193
1194
			var data = {
1195
				action: "attribute_entity_set_selection",
1196
				current_entity_id: jQuery(this).val(),
1197
				wpshop_ajax_nonce: "' . wp_create_nonce("wpshop_attribute_entity_set_selection") . '"
1198
			};
1199
			jQuery.post(ajaxurl, data, function(response) {
1200
				jQuery(".wpshop_attributes_edition_table_field_input_set_section").html( response );
1201
			}, "json");
1202
		});
1203
1204
1205
		jQuery("#wpshop_attributes_edition_table_field_id_is_used_for_variation").click(function(){
1206
			if ( jQuery(this).is(":checked") ) {
1207
				jQuery("#wpshop_attributes_edition_table_field_id_is_used_in_variation").prop("checked", false);
1208
				jQuery("#wpshop_attributes_edition_table_field_id_is_used_in_variation").prop("disabled", true);
1209
			}
1210
			else {
1211
				jQuery("#wpshop_attributes_edition_table_field_id_is_used_in_variation").prop("disabled", false);
1212
			}
1213
		});
1214
	});
1215
	function change_unit_list(){
1216
		var data = {
1217
					action: "load_attribute_unit_list",
1218
					wpshop_ajax_nonce: jQuery("#input_wpshop_load_attribute_unit_list").val(),
1219
					current_group: jQuery("#wpshop_attributes_edition_table_field_id__unit_group_id").val(),
1220
					selected_list:"unit"
1221
				};
1222
			//Response, update the combo box
1223
				jQuery.post(ajaxurl, data, function(response) {
1224
					if ( response[0] ) {
1225
						jQuery("#wpshop_attributes_edition_table_field_id__default_unit").html(response[1]);
1226
					}
1227
					else {
1228
						alert( response[1] );
1229
					}
1230
				}, "json");
1231
1232
	}
1233
</script>';
1234
1235
1236
1237
1238
1239
		return $the_form;
1240
	}
1241
	/**
1242
	 *	Return the different button to save the item currently being added or edited
1243
	 *
1244
	 *	@return string $currentPageButton The html output code with the different button to add to the interface
1245
	 */
1246
	function getPageFormButton($element_id = 0){
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...
1247
		$action = isset($_REQUEST['action']) ? sanitize_text_field($_REQUEST['action']) : 'add';
1248
		$currentPageButton = '';
1249
1250
		 //$currentPageButton .= '<h2 class="cancelButton alignleft" ><a href="' . admin_url('edit.php?post_type='.WPSHOP_NEWTYPE_IDENTIFIER_ENTITIES.'&amp;page=' . self::getListingSlug()) . '" class="button add-new-h2" >' . __('Back', 'wpshop') . '</a></h2>';
0 ignored issues
show
Unused Code Comprehensibility introduced by
41% 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...
1251
1252 View Code Duplication
		if(($action == 'add') && (current_user_can('wpshop_add_attributes')))
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...
1253
			$currentPageButton .= '<input type="button" class="button-primary" id="add" name="add" value="' . __('Add', 'wpshop') . '" />';
1254
1255
		elseif(current_user_can('wpshop_edit_attributes'))
1256
		$currentPageButton .= '<input type="button" class="button-primary" id="save" name="save" value="' . __('Save', 'wpshop') . '" />';
1257
1258
		$attribute_undeletable = unserialize(WPSHOP_ATTRIBUTE_UNDELETABLE);
1259
		$attribute = self::getElement($element_id, "'valid', 'moderated', 'notused'", 'id');
1260
		$attribute_code = !empty($attribute->code)?$attribute->code:'';
1261
		if(current_user_can('wpshop_delete_attributes') && ($action != 'add') && !in_array($attribute_code, $attribute_undeletable))
1262
			$currentPageButton .= '<input type="button" class="button-secondary wpshop_delete_element_button wpshop_delete_element_button_'.self::currentPageCode.'" id="delete" name="delete" value="' . __('Delete', 'wpshop') . '" />';
1263
1264
		return $currentPageButton;
1265
	}
1266
1267
	/**
1268
	 *	Get the existing attribute list into database
1269
	 *
1270
	 *	@param integer $element_id optionnal The attribute identifier we want to get. If not specify the entire list will be returned
1271
	 *	@param string $element_status optionnal The status of element to get into database. Default is set to valid element
1272
	 *	@param mixed $field_to_search optionnal The field we want to check the row identifier into. Default is to set id
1273
	 *
1274
	 *	@return object $element_list A wordpress database object containing the attribute list
1275
	 */
1276
	public static function getElement($element_id = '', $element_status = "'valid', 'moderated', 'notused'", $field_to_search = 'id', $list = false){
1277
1278
		global $wpdb;
1279
		$element_list = array();
0 ignored issues
show
Unused Code introduced by
$element_list 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...
1280
		$moreQuery = "";
1281
		$moreArgs = array( 1, );
1282
1283
		$orderby = !empty( $_REQUEST['orderby'] ) ? sanitize_text_field( $_REQUEST['orderby'] ) : '';
1284
		$order = !empty( $_REQUEST['order'] ) ? sanitize_text_field( $_REQUEST['order'] ) : '';
1285
1286
		if($element_id != ''){
1287
			$moreQuery .= "
1288
					AND CURRENT_ELEMENT." . $field_to_search . " = %s ";
1289
			$moreArgs[] = $element_id;
1290
		}
1291
		if(!empty($orderby) && !empty($order)){
1292
			$moreQuery .= "
1293
					ORDER BY " . $orderby . "  " . $order;
1294
		}
1295
1296
		$query = $wpdb->prepare(
1297
			"SELECT CURRENT_ELEMENT.*, ENTITIES.post_name as entity
1298
			FROM " . self::getDbTable() . " AS CURRENT_ELEMENT
1299
			INNER JOIN {$wpdb->posts} AS ENTITIES ON (ENTITIES.ID = CURRENT_ELEMENT.entity_id)
1300
			WHERE %d AND CURRENT_ELEMENT.status IN (".$element_status.") " . $moreQuery,
1301
			$moreArgs
1302
		);
1303
1304
		/*	Get the query result regarding on the function parameters. If there must be only one result or a collection	*/
1305
		if(($element_id == '') || $list){
1306
			$element_list = $wpdb->get_results($query);
1307
		}
1308
		else{
1309
			$element_list = $wpdb->get_row($query);
1310
		}
1311
1312
		return $element_list;
1313
	}
1314
1315
	/**
1316
	 *	Save the different value for attribute of a given entity type and entity
1317
	 *
1318
	 *	@param array $attributeToSet The list of attribute with each value to set like this : ['integer']['tx_tva'] = 10
1319
	 *	@param integer $entityTypeId The entity type identifier (products/categories/...)
1320
	 *	@param integer $entityId The entity identifier we want to save attribute for (The specific product/category/...)
1321
	 *	@param string $language The language to set the value for into database
1322
	 *
1323
	 */
1324
	public static function saveAttributeForEntity($attributeToSet, $entityTypeId, $entityId, $language = WPSHOP_CURRENT_LOCALE, $from = '') {
1325
		global $wpdb;
1326
		/* Recuperation de l'identifiant de l'utilisateur connecte */
1327
		$user_id = function_exists('is_user_logged_in') && is_user_logged_in() ? get_current_user_id() : '0';
1328
		$sent_attribute_list = array();
1329
1330
		if ( !empty($attributeToSet) ) {
1331
			$attributeToSet = apply_filters( 'save_attribute_for_entity', $attributeToSet, $entityTypeId, $entityId );
1332
			$old_attribute_to_set = $attributeToSet;
1333
			$attribute_setted = array();
1334
			foreach ($attributeToSet as $attributeType => $attributeTypeDetails) {
1335
				/** Preparation des parametres permettant de supprimer les bonnes valeurs des attributs suivant la configuration de la boutique et de la methode de mise a jour */
1336
				$delete_current_attribute_values_params = array(
1337
					'entity_id' => $entityId,
1338
					'entity_type_id' => $entityTypeId
1339
				);
1340
				if ( WPSHOP_ATTRIBUTE_VALUE_PER_USER ) {
1341
					$delete_current_attribute_values_params['user_id'] = $user_id;
1342
				}
1343
1344
				if(!empty($attributeTypeDetails) && is_array($attributeTypeDetails)) {
1345
					$attributeTypeDetails = apply_filters( "save_attribute_for_entity_{$attributeType}", $attributeTypeDetails, $entityTypeId, $entityId );
1346
					foreach($attributeTypeDetails as $attribute_code => $attributeValue) {
1347
						$attributeValue = apply_filters( "save_attribute_for_entity_{$attributeType}_{$attribute_code}", apply_filters( "save_attribute_for_entity__{$attribute_code}", $attributeValue, $entityTypeId, $entityId ), $entityTypeId, $entityId );
1348
						$old_attribute_value = $attributeValue;
1349
1350
						if ( $attributeType == 'decimal' ) {
1351
							$attributeValue = str_replace(',', '.', $attributeValue);
1352
						}
1353
						if ( ($attributeType == 'integer') && !is_array($attributeValue) ) {
1354
							$attributeValue = (int)$attributeValue;
1355
						}
1356
						$more_query_params_values = array();
0 ignored issues
show
Unused Code introduced by
$more_query_params_values 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...
1357
						if($attribute_code != 'unit') {
1358
1359
							$unit_id = 0;
1360
							if(isset($attributeTypeDetails['unit'][$attribute_code])){
1361
								$unit_id = $attributeTypeDetails['unit'][$attribute_code];
1362
							}
1363
1364
							$currentAttribute = self::getElement($attribute_code, "'valid'", 'code');
1365
							if( !empty($currentAttribute) ){
1366
								$sent_attribute_list[] = $currentAttribute->id;
1367
1368
								/*	Enregistrement de la valeur actuelle de l'attribut dans la table d'historique si l'option historique est activee sur l'attribut courant	*/
1369
								if (  $currentAttribute->is_historisable == 'yes') {
1370
									$query = $wpdb->prepare("SELECT * FROM " . WPSHOP_DBT_ATTRIBUTE_VALUES_PREFIX . $attributeType . " WHERE entity_type_id = %d AND attribute_id = %d AND entity_id = %d", $entityTypeId, $currentAttribute->id, $entityId);
1371
									$attribute_histo = $wpdb->get_results($query);
1372
									if(!empty($attribute_histo)){
1373
										$attribute_histo_content['status'] = 'valid';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$attribute_histo_content was never initialized. Although not strictly required by PHP, it is generally a good practice to add $attribute_histo_content = 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...
1374
										$attribute_histo_content['creation_date'] = current_time('mysql', 0);
0 ignored issues
show
Bug introduced by
The variable $attribute_histo_content 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...
1375
										$attribute_histo_content['creation_date_value'] = $attribute_histo[0]->creation_date_value;
1376
										$attribute_histo_content['original_value_id'] = $attribute_histo[0]->value_id;
1377
										$attribute_histo_content['entity_type_id'] = $attribute_histo[0]->entity_type_id;
1378
										$attribute_histo_content['attribute_id'] = $attribute_histo[0]->attribute_id;
1379
										$attribute_histo_content['entity_id'] = $attribute_histo[0]->entity_id;
1380
										$attribute_histo_content['unit_id'] = $attribute_histo[0]->unit_id;
1381
										$attribute_histo_content['user_id'] = $attribute_histo[0]->user_id;
1382
										$attribute_histo_content['language'] = $attribute_histo[0]->language;
1383
										$attribute_histo_content['value'] = $attribute_histo[0]->value;
1384
										$attribute_histo_content['value_type'] = WPSHOP_DBT_ATTRIBUTE_VALUES_PREFIX . $attributeType;
1385
										$wpdb->insert(WPSHOP_DBT_ATTRIBUTE_VALUES_HISTO, $attribute_histo_content);
1386
									}
1387
								}
1388
								$attributeValue = str_replace("\\", "", $attributeValue);
1389
1390
								if ( empty($from) || (!empty($attributeValue)) ) {
1391
									$wpdb->delete(WPSHOP_DBT_ATTRIBUTE_VALUES_PREFIX.$attributeType, array_merge($delete_current_attribute_values_params, array('attribute_id' => $currentAttribute->id)));
1392
1393
									/**	Insertion de la nouvelle valeur de l'attribut dans la base	*/
1394
									$query_params = array(
1395
										'value_id' => '',
1396
										'entity_type_id' => $entityTypeId,
1397
										'attribute_id' => $currentAttribute->id,
1398
										'entity_id' => $entityId,
1399
										'unit_id' => $unit_id,
1400
										'language' => $language,
1401
										'user_id' => $user_id,
1402
										'creation_date_value' => current_time('mysql', 0)
1403
									);
1404
									/**	Si l'attribut courant est contenu dans un tableau (exemple: select multiple) on lit tout le tableau et on enregistre chaque valeur separement	*/
1405
									if(is_array($attributeValue)){
1406
										foreach($attributeValue as $a){
1407
											$wpdb->insert(WPSHOP_DBT_ATTRIBUTE_VALUES_PREFIX.$attributeType, array_merge($query_params, array('value' => $a)));
1408
										}
1409
									}
1410
									else{
1411
										$wpdb->insert(WPSHOP_DBT_ATTRIBUTE_VALUES_PREFIX.$attributeType, array_merge($query_params, array('value' => $attributeValue)));
1412
										\eoxia\log_class::exec( 'wpshop_attributes', 'wpshop_attributes', __( 'Add the attribute : ' . $currentAttribute->code . ' with value : ' . $attributeValue , 'wpshop' ), array( 'object_id' 	=> $entityId ), 0 );
1413
									}
1414
1415
									/**	Dans le cas ou l'attribut courant est utilise dans l'interface permettant de trier les produits (option de l'attribut) on defini une meta specifique	*/
1416
									if ( ( ($currentAttribute->is_used_for_sort_by == 'yes') || ($currentAttribute->is_searchable == 'yes'))  || ( $currentAttribute->is_filterable == 'yes') && !empty($attributeValue) ) :
1417
										update_post_meta($entityId, '_'.$attribute_code, $attributeValue);
1418
									endif;
1419
1420
									/**	Enregistrement de toutes les valeurs des attributs dans une meta du produit	*/
1421
									$attribute_option = (!empty($_POST['attribute_option'][$attribute_code])) ? (array) $_POST['attribute_option'][$attribute_code] : null;
1422
									if (isset($attribute_option)) {
1423
										$value = self::get_attribute_type_select_option_info($attributeTypeDetails[$attribute_code], 'value');
1424
										if (strtolower($value) == 'yes') :
1425
											update_post_meta($entityId, 'attribute_option_'.$attribute_code, $attribute_option);
1426
										else :
1427
											delete_post_meta($entityId, 'attribute_option_'.$attribute_code);
1428
										endif;
1429
									}
1430
								}
1431
							}
1432
						}
1433
						do_action( "saved_attribute_for_entity_{$attributeType}_{$attribute_code}", $attributeValue, $old_attribute_value, $entityTypeId, $entityId );
1434
						do_action( "saved_attribute_for_entity__{$attribute_code}", $attributeValue, $old_attribute_value, $entityTypeId, $entityId );
1435
						if ( isset( $attribute_setted[$attributeType][$attribute_code] ) ) {
1436
							if( is_array( $attribute_setted[$attributeType][$attribute_code] )) {
1437
								$attribute_setted[$attributeType][$attribute_code][] = $attributeValue;
1438
							} else {
1439
								$attribute_setted[$attributeType][$attribute_code] = array( $attribute_setted[$attributeType][$attribute_code], $attributeValue );
1440
							}
1441
						} else {
1442
							$attribute_setted[$attributeType][$attribute_code] = $attributeValue;
1443
						}
1444
					}
1445
1446
					if ( empty($from) ) {
1447
						$query = $wpdb->prepare("SELECT value_id FROM " . WPSHOP_DBT_ATTRIBUTE_VALUES_PREFIX.$attributeType . " WHERE attribute_id NOT IN ('" . implode("', '", $sent_attribute_list) . "') AND entity_id = %d AND entity_type_id = %d", $entityId, $entityTypeId);
1448
						$attr_to_delete = $wpdb->get_results($query);
1449
						if(!empty($attr_to_delete)){
1450
							foreach ($attr_to_delete as $value) {
1451
								$wpdb->delete(WPSHOP_DBT_ATTRIBUTE_VALUES_PREFIX.$attributeType, array_merge($delete_current_attribute_values_params, array('value_id' => $value->value_id)));
1452
								\eoxia\log_class::exec( 'wpshop_attributes', 'wpshop_attributes', __( 'Remove the attribute : ' . $value->value_id, 'wpshop' ), array( 'object_id' 	=> $entityId ), 0 );
1453
							}
1454
						}
1455
					}
1456
				}
1457
			}
1458
			do_action( "saved_attribute_for_entity", $attribute_setted, $old_attribute_to_set, $entityTypeId, $entityId );
1459
		}
1460
	}
1461
1462
	/**
1463
	 *	Return the value for a given attribute of a given entity type and a given entity
1464
	 *
1465
	 *	@param string $attributeType The extension of the database table to get the attribute value in
1466
	 *	@param integer $attributeId The attribute identifier we want to get the value for
1467
	 *	@param integer $entityTypeId The entity type identifier we want to get the attribute value for (example: product = 1)
1468
	 	*	@param integer $entityId The entity id we want the attribute value for
1469
	 *
1470
	 *	@return object $attributeValue A wordpress database object containing the value of the attribute for the selected entity
1471
	 */
1472
	public static function getAttributeValueForEntityInSet($attributeType, $attributeId, $entityTypeId, $entityId, $atribute_params = array()) {
1473
		global $wpdb;
1474
		$attributeValue = '';
0 ignored issues
show
Unused Code introduced by
$attributeValue 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...
1475
1476
		$query_params = "";
1477
		$query_params_values = array($attributeId, $entityTypeId, $entityId);
1478
		if(WPSHOP_ATTRIBUTE_VALUE_PER_USER && (isset($atribute_params['intrinsic']) && ($atribute_params['intrinsic'] != 'yes'))){
1479
			$query_params = "
1480
				AND ATTR_VAL.user_id = %d";
1481
			$query_params_values[] = get_current_user_id();
1482
		}
1483
		$query = $wpdb->prepare(
1484
			"SELECT ATTR_VAL.value, ATTR_VAL.unit_id, ATTR_VAL.user_id
1485
			FROM " . WPSHOP_DBT_ATTRIBUTE_VALUES_PREFIX . $attributeType . " AS ATTR_VAL
1486
			WHERE ATTR_VAL.attribute_id = %d
1487
				AND ATTR_VAL.entity_type_id = %d
1488
				AND ATTR_VAL.entity_id = %d" . $query_params . "
1489
			ORDER BY ATTR_VAL.creation_date_value ASC",
1490
			$query_params_values
1491
		);
1492
		$attributeValue = $wpdb->get_results($query);
1493
1494
		if ( ( (count($attributeValue) <= 1 ) && !empty($attributeValue[0]) ) && ( empty($atribute_params['frontend_input']) || ($atribute_params['frontend_input'] != 'multiple-select') )) {
1495
			$attributeValue = $attributeValue[0];
1496
		}
1497
		else{
1498
			$entity_meta = get_post_meta($entityId, WPSHOP_PRODUCT_ATTRIBUTE_META_KEY, true);
1499
			if ( !empty($entity_meta) ) {
1500
				$query = $wpdb->prepare("SELECT code FROM " . WPSHOP_DBT_ATTRIBUTE . " WHERE id = %d AND entity_id = %d ", $attributeId, $entityTypeId);
1501
				$attribute_code = $wpdb->get_var($query);
1502
				$attributeValue = !empty($entity_meta[$attribute_code]) ? $entity_meta[$attribute_code] : null;
1503
			}
1504
			if ( is_array($attributeValue) ) {
1505
				$tmp_array = array();
1506
				if ( !empty($attributeValue) ) {
1507
					foreach ( $attributeValue as $att ) {
1508
						$obj = new stdClass();
1509
						$obj->value = $att;
1510
						$obj->unit_id = 0;
1511
						$obj->user_id = get_current_user_id();
1512
						$tmp_array[] = $obj;
1513
					}
1514
					$attributeValue = $tmp_array;
1515
				}
1516
			}
1517
		}
1518
// 		if(!WPSHOP_ATTRIBUTE_VALUE_PER_USER && (count($attributeValue) > 1)){
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...
1519
// 			$attributeValue = $attributeValue[0];
1520
// 		}
1521
1522
		return $attributeValue;
1523
	}
1524
1525
	/**
1526
	 *	Get the existing element list into database
1527
	 *
1528
	 *	@param integer $elementId optionnal The element identifier we want to get. If not specify the entire list will be returned
1529
	 *	@param string $elementStatus optionnal The status of element to get into database. Default is set to valid element
0 ignored issues
show
Bug introduced by
There is no parameter named $elementStatus. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

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

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

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

Loading history...
1530
	 *
1531
	 *	@return object $elements A wordpress database object containing the element list
1532
	 */
1533
	public static function getElementWithAttributeAndValue($entityId, $elementId, $language, $keyForArray = '', $outputType = '') {
0 ignored issues
show
Unused Code introduced by
The parameter $outputType 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...
1534
		global $wpdb;
1535
		$elements = array();
1536
		$elementsWithAttributeAndValues = self::get_attribute_list_for_item($entityId, $elementId, $language);
1537
1538
		foreach ( $elementsWithAttributeAndValues as $elementDefinition ) {
1539
			$arrayKey = $elementDefinition->attribute_id;
1540
			if ( $keyForArray == 'code' ) {
1541
				$arrayKey = $elementDefinition->attribute_code;
1542
			}
1543
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['code'] = $elementDefinition->attribute_set_section_code;
1544
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['display_on_frontend'] = $elementDefinition->display_on_frontend;
1545
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['code'] = $elementDefinition->code;
1546
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['data_type'] = $elementDefinition->data_type;
1547
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['backend_table'] = $elementDefinition->backend_table;
1548
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['backend_input'] = $elementDefinition->backend_input;
1549
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['frontend_input'] = $elementDefinition->frontend_input;
1550
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['frontend_label'] = __( $elementDefinition->frontend_label, 'wpshop' );
1551
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['attribute_code'] = $elementDefinition->attribute_code;
1552
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['data_type_to_use'] = $elementDefinition->data_type_to_use;
1553
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['is_visible_in_front'] = $elementDefinition->is_visible_in_front;
1554
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['is_visible_in_front_listing'] = $elementDefinition->is_visible_in_front_listing;
1555
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['is_requiring_unit'] = $elementDefinition->is_requiring_unit;
1556
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['is_used_in_quick_add_form'] = $elementDefinition->is_used_in_quick_add_form;
1557
			$attributeValueField = 'attribute_value_' . $elementDefinition->data_type;
1558
1559
			// Manage the value differently if it is an array or not
1560
			if ( !empty($elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['value']) ) {
1561
				if (is_array($elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['value'])) {
1562
					$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['value'][] = $elementDefinition->$attributeValueField;
1563
				}
1564
				else {
1565
					$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['value'] = array($elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['value'],$elementDefinition->$attributeValueField);
1566
				}
1567
			}
1568
			else {
1569
				$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['value'] = $elementDefinition->$attributeValueField;
1570
			}
1571
1572
			if ( $elementDefinition->backend_input == 'multiple-select' ) {
1573
				$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['select_value'] = self::get_attribute_type_select_option_info($attributeValueField, 'value');
1574
			}
1575
1576
			$attributeUnitField = 'attribute_unit_' . $elementDefinition->data_type;
1577
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['unit'] = __( $elementDefinition->$attributeUnitField, 'wpshop' );
1578
			if( !empty($elementDefinition->is_requiring_unit ) && ( $elementDefinition->is_requiring_unit == 'yes' ) && empty( $elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['unit'] ) ) {
1579
				$unit = '';
0 ignored issues
show
Unused Code introduced by
$unit 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...
1580
				$query = $wpdb->prepare( 'SELECT unit FROM '. WPSHOP_DBT_ATTRIBUTE_UNIT . ' WHERE id = %d AND status = %s', $elementDefinition->_default_unit, 'valid');
1581
				$unit = $wpdb->get_var( $query );
1582
				$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['unit'] = __( $unit, 'wpshop' );
1583
			}
1584
1585
		}
1586
		return $elements;
1587
	}
1588
1589
	public static function get_attribute_list_for_item($entityId, $elementId, $language = WPSHOP_CURRENT_LOCALE, $defined_entity_type = '', $ead_status = "'valid', 'deleted'") {
0 ignored issues
show
Unused Code introduced by
The parameter $language 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...
1590
		global $wpdb;
1591
		$elementsWithAttributeAndValues = array();
0 ignored issues
show
Unused Code introduced by
$elementsWithAttributeAndValues 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...
1592
		$moreQuery = "";
1593
1594
		$entity_type = empty($defined_entity_type) ? get_post_type( $elementId ) : $defined_entity_type;
1595
1596
		$query = $wpdb->prepare(
1597
				"SELECT POST_META.*,
1598
					ATTR.code, ATTR.id as attribute_id, ATTR.data_type, ATTR.backend_table, ATTR.backend_input, ATTR.frontend_input, ATTR.frontend_label, ATTR.code AS attribute_code, ATTR.is_recordable_in_cart_meta, ATTR.default_value as default_value, ATTR.data_type_to_use, ATTR.is_visible_in_front, ATTR.is_filterable, ATTR.is_visible_in_front_listing, ATTR.is_requiring_unit, ATTR.is_used_in_quick_add_form,
1599
					ATTR_VALUE_VARCHAR.value AS attribute_value_varchar, ATTR_UNIT_VARCHAR.unit AS attribute_unit_varchar,
1600
					ATTR_VALUE_DECIMAL.value AS attribute_value_decimal, ATTR_UNIT_DECIMAL.unit AS attribute_unit_decimal,
1601
					ATTR_VALUE_TEXT.value AS attribute_value_text, ATTR_UNIT_TEXT.unit AS attribute_unit_text,
1602
					ATTR_VALUE_INTEGER.value AS attribute_value_integer, ATTR_UNIT_INTEGER.unit AS attribute_unit_integer,
1603
					ATTR_VALUE_DATETIME.value AS attribute_value_datetime, ATTR_UNIT_DATETIME.unit AS attribute_unit_datetime,
1604
					ATTRIBUTE_GROUP.code AS attribute_set_section_code, ATTRIBUTE_GROUP.name AS attribute_set_section_name, ATTRIBUTE_GROUP.display_on_frontend, ATTR._unit_group_id, ATTR._default_unit
1605
				FROM " . WPSHOP_DBT_ATTRIBUTE . " AS ATTR
1606
					LEFT JOIN " . WPSHOP_DBT_ATTRIBUTE_DETAILS . " AS EAD ON (EAD.attribute_id = ATTR.id)
1607
					INNER JOIN " . $wpdb->postmeta . " AS POST_META ON ((POST_META.post_id = %d) AND (POST_META.meta_key = '_" . $entity_type . "_attribute_set_id') AND (POST_META.meta_value = EAD.attribute_set_id))
1608
					LEFT JOIN " . WPSHOP_DBT_ATTRIBUTE_GROUP . " AS ATTRIBUTE_GROUP  ON (ATTRIBUTE_GROUP.id = EAD.attribute_group_id)
1609
					LEFT JOIN " . WPSHOP_DBT_ATTRIBUTE_VALUES_VARCHAR . " AS ATTR_VALUE_VARCHAR ON ((ATTR_VALUE_VARCHAR.entity_type_id = '" . $entityId . "') AND (ATTR_VALUE_VARCHAR.attribute_id = ATTR.id) AND (ATTR_VALUE_VARCHAR.entity_id = %d) )
1610
					LEFT JOIN " . WPSHOP_DBT_ATTRIBUTE_UNIT . " AS ATTR_UNIT_VARCHAR ON ((ATTR_UNIT_VARCHAR.id = ATTR_VALUE_VARCHAR.unit_id) AND (ATTR_UNIT_VARCHAR.status = 'valid'))
1611
					LEFT JOIN " . WPSHOP_DBT_ATTRIBUTE_VALUES_DECIMAL . " AS ATTR_VALUE_DECIMAL ON ((ATTR_VALUE_DECIMAL.entity_type_id = '" . $entityId . "') AND (ATTR_VALUE_DECIMAL.attribute_id = ATTR.id) AND (ATTR_VALUE_DECIMAL.entity_id = %d) )
1612
					LEFT JOIN " . WPSHOP_DBT_ATTRIBUTE_UNIT . " AS ATTR_UNIT_DECIMAL ON ((ATTR_UNIT_DECIMAL.id = ATTR_VALUE_DECIMAL.unit_id) AND (ATTR_UNIT_DECIMAL.status = 'valid'))
1613
					LEFT JOIN " . WPSHOP_DBT_ATTRIBUTE_VALUES_TEXT . " AS ATTR_VALUE_TEXT ON ((ATTR_VALUE_TEXT.entity_type_id = '" . $entityId . "') AND (ATTR_VALUE_TEXT.attribute_id = ATTR.id) AND (ATTR_VALUE_TEXT.entity_id = %d) )
1614
					LEFT JOIN " . WPSHOP_DBT_ATTRIBUTE_UNIT . " AS ATTR_UNIT_TEXT ON ((ATTR_UNIT_TEXT.id = ATTR_VALUE_TEXT.unit_id) AND (ATTR_UNIT_TEXT.status = 'valid'))
1615
					LEFT JOIN " . WPSHOP_DBT_ATTRIBUTE_VALUES_INTEGER . " AS ATTR_VALUE_INTEGER ON ((ATTR_VALUE_INTEGER.entity_type_id = '" . $entityId . "') AND (ATTR_VALUE_INTEGER.attribute_id = ATTR.id) AND (ATTR_VALUE_INTEGER.entity_id = %d))
1616
					LEFT JOIN " . WPSHOP_DBT_ATTRIBUTE_UNIT . " AS ATTR_UNIT_INTEGER ON ((ATTR_UNIT_INTEGER.id = ATTR_VALUE_INTEGER.unit_id) AND (ATTR_UNIT_INTEGER.status = 'valid'))
1617
					LEFT JOIN " . WPSHOP_DBT_ATTRIBUTE_VALUES_DATETIME . " AS ATTR_VALUE_DATETIME ON ((ATTR_VALUE_DATETIME.entity_type_id = '" . $entityId . "') AND (ATTR_VALUE_DATETIME.attribute_id = ATTR.id) AND (ATTR_VALUE_DATETIME.entity_id = %d) )
1618
					LEFT JOIN " . WPSHOP_DBT_ATTRIBUTE_UNIT . " AS ATTR_UNIT_DATETIME ON ((ATTR_UNIT_DATETIME.id = ATTR_VALUE_DATETIME.unit_id) AND (ATTR_UNIT_DATETIME.status = 'valid'))
1619
				WHERE
1620
					ATTR.status = 'valid'
1621
					AND EAD.status IN ( " . $ead_status . " )
1622
					AND ATTRIBUTE_GROUP.status = 'valid'
1623
					AND EAD.entity_type_id = '" . $entityId . "' " . $moreQuery . "
1624
			ORDER BY ATTRIBUTE_GROUP.position",
1625
		$elementId, $elementId, $elementId, $elementId, $elementId, $elementId);
1626
1627
		$elementsWithAttributeAndValues = $wpdb->get_results($query);
1628
1629
		return $elementsWithAttributeAndValues;
1630
	}
1631
1632
	/**
1633
	 * Check if an attribute or an attribute set section have to be displayed on the product output un frontend
1634
	 *
1635
	 * @param string $attribute_main_config The main configuration for display for the attribute
1636
	 * @param array $attribute_custom_config The custom config defined into product page
1637
	 * @param string $attribute_or_set Define if we check for an attribute or for an attribute set section
1638
	 * @param string $attribute_code The code of element to check the display for
1639
	 * @param string $output_type The current output type
1640
	 *
1641
	 * @return boolean The result to know if the element has to be displayed on frontend
1642
	 */
1643
	public static function check_attribute_display( $attribute_main_config, $attribute_custom_config, $attribute_or_set, $attribute_code, $output_type) {
1644
		if ( $attribute_main_config === 'yes' ) {
1645
			$attribute_output = true;
1646
			if ( ( is_array($attribute_custom_config) && in_array($attribute_or_set, array('attribute', 'attribute_set_section', 'product_action_button')) && !empty($attribute_custom_config[$attribute_or_set]) && !empty($attribute_custom_config[$attribute_or_set][$attribute_code]) && !empty($attribute_custom_config[$attribute_or_set][$attribute_code][$output_type]) && $attribute_custom_config[$attribute_or_set][$attribute_code][$output_type] == 'yes' )
1647
				 || empty($attribute_custom_config) ) {
1648
				$attribute_output = true;
1649
			}
1650
			else if ( empty($attribute_custom_config[$attribute_or_set][$attribute_code]) || empty($attribute_custom_config[$attribute_or_set][$attribute_code][$output_type]) || (!empty($attribute_custom_config[$attribute_or_set][$attribute_code][$output_type]) && ( $attribute_custom_config[$attribute_or_set][$attribute_code][$output_type] == 'no')) )  {
1651
				$attribute_output = false;
1652
			}
1653
		}
1654
		elseif ( $attribute_main_config === 'no' ) {
1655
			$attribute_output = false;
1656
			if ( empty($attribute_custom_config[$attribute_or_set]) || empty($attribute_custom_config[$attribute_or_set][$attribute_code]) ) {
1657
				$attribute_output = false;
1658
			}
1659
			else if ( !empty($attribute_custom_config) && !empty($attribute_custom_config[$attribute_or_set]) && !empty($attribute_custom_config[$attribute_or_set][$attribute_code]) && !empty($attribute_custom_config[$attribute_or_set][$attribute_code][$output_type]) && ( $attribute_custom_config[$attribute_or_set][$attribute_code][$output_type] == 'yes') )  {
1660
				$attribute_output = true;
1661
			}
1662
		}
1663
1664
		return $attribute_output;
0 ignored issues
show
Bug introduced by
The variable $attribute_output 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...
1665
	}
1666
1667
	/**
1668
	 * Traduit le shortcode et affiche la valeur d'un attribut donn�
1669
	 * @param array $atts : tableau de param�tre du shortcode
1670
	 * @return mixed
1671
	 **/
1672
	public static function wpshop_att_val_func($atts) {
1673
		global $wpdb;
1674
		global $wp_query;
1675
1676
		$attribute = self::getElement( $atts['attid'] );
1677
		if(empty($atts['pid'])) $atts['pid'] = $wp_query->posts[0]->ID;
1678
		$attribute_main_config = ( empty($atts['output_type']) || ($atts['output_type'] == 'complete_sheet') ) ? $attribute->is_visible_in_front : $attribute->is_visible_in_front_listing;
1679
		$output_type = ( empty($atts['output_type']) || ($atts['output_type'] == 'complete_sheet') ) ? 'complete_sheet' : 'mini_output';
1680
		$product_attribute_custom_config = get_post_meta($atts['pid'], WPSHOP_PRODUCT_FRONT_DISPLAY_CONF, true);
1681
		$display_attribute_value = wpshop_attributes::check_attribute_display( $attribute_main_config, $product_attribute_custom_config, 'attribute', $attribute->code, $output_type);
0 ignored issues
show
Unused Code introduced by
$display_attribute_value 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...
1682
1683
		if ( !empty( $attribute->data_type ) ) {
1684
			$attributeDefinition['unit'] = '';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$attributeDefinition was never initialized. Although not strictly required by PHP, it is generally a good practice to add $attributeDefinition = 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...
1685
1686
			$has_value = false;
1687
			$query = $wpdb->prepare("SELECT value FROM " . WPSHOP_DBT_ATTRIBUTE_VALUES_PREFIX . $attribute->data_type . " WHERE entity_id=%s AND attribute_id=%d", $atts['pid'], $atts['attid'] );
1688
			if ( in_array($attribute->backend_input, array('multiple-select', 'checkbox')) ) {
1689
				$list_of_value = $wpdb->get_results($query);
1690
				if ( !empty($list_of_value) ) {
1691
					foreach ( $list_of_value as $value ) {
1692
						$data[] = $value->value;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = 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...
1693
					}
1694
					$has_value = true;
1695
				}
1696
			}
1697
			else {
1698
				$data = $wpdb->get_var($query);
1699
				if ( !empty($data) ) {
1700
					$has_value = true;
1701
				}
1702
				elseif( !empty($attribute->default_value) ) {
1703
					$has_value = true;
1704
					$data = $attribute->default_value;
1705
				}
1706
			}
1707
			$attributeDefinition['value'] = is_array($data) ? array_reverse($data) : $data;
0 ignored issues
show
Bug introduced by
The variable $data 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...
1708
1709
			$attributeDefinition['data_type'] = $attribute->data_type;
1710
			$attributeDefinition['code'] = $attribute->code;
1711
			$attributeDefinition['is_requiring_unit'] = $attribute->is_requiring_unit;
1712
			$attributeDefinition['backend_input'] = $attribute->backend_input;
1713
			$attributeDefinition['data_type_to_use'] = $attribute->data_type_to_use;
1714
			$attribute_display = wpshop_attributes::wps_attribute_values_display( $attributeDefinition );
0 ignored issues
show
Documentation introduced by
$attributeDefinition is of type array<string,?,{"data_type_to_use":"?"}>, 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...
1715
			$attribute_value = $attribute_display[0];
1716
			$attributeDefinition['value'] = $attribute_display[1];
1717
			$attribute_unit_list = $attribute_display[2];
1718
1719
			$result = (!empty($atts) && !empty($atts['with_label']) && ($atts['with_label'] == 'yes') ? $attribute->frontend_label . ' : ' : '') . $attribute_value . ' ' . $attribute_unit_list;
1720
1721
			return $has_value ? $result : '';
1722
		}
1723
1724
		return null;
1725
	}
1726
	/**
1727
	 * Build the output for an attribute field
1728
	 *
1729
	 * @param object $attribute The complete definition for an attribute
1730
	 * @param string $attribute_value Optionnal The current value for the attribute
1731
	 * @param array $specific_argument Optionnal The different parameters used for filter output
1732
	 * @return array The definition for the field used to display an attribute
1733
	 */
1734
	public static function get_attribute_field_definition( $attribute, $attribute_value = '', $specific_argument = array() ) {
1735
		global $wpdb;
1736
		$wpshop_price_attributes = unserialize(WPSHOP_ATTRIBUTE_PRICES);
1737
		$wpshop_weight_attributes = unserialize(WPSHOP_ATTRIBUTE_WEIGHT);
1738
		$input_def = array();
1739
		$input_def['option'] = $input_def['field_container_class'] = '';
1740
		$attributeInputDomain = (!empty($specific_argument['field_custom_name_prefix']) || (!empty($specific_argument['field_custom_name_prefix']) && ($specific_argument['field_custom_name_prefix'] == 'empty')) ) ? $specific_argument['field_custom_name_prefix'] : ((!empty($specific_argument['page_code']) ? $specific_argument['page_code'] . '_' : '' ) . 'attribute[' . $attribute->data_type . ']');
1741
		$input_def['input_domain'] = $attributeInputDomain;
1742
		$input_def['id'] = (!empty($specific_argument) && !empty($specific_argument['field_id']) ? $specific_argument['field_id'] . '_' : '') . 'attribute_' . $attribute->id;
1743
		$input_def['intrinsec'] = $attribute->is_intrinsic;
1744
		$input_def['name'] = $attribute->code;
1745
		$input_def['type'] = wpshop_tools::defineFieldType($attribute->data_type, $attribute->frontend_input, $attribute->frontend_verification);
1746
		$input_def['label'] = $attribute->frontend_label;
1747
		$attribute_default_value = stripslashes($attribute->default_value);
1748
		$input_def['value'] = $attribute_default_value;
1749
		$input_def['default_value'] = $attribute_default_value;
1750
		$input_def['is_unique'] = $attribute->is_unique;
1751
		$input_def['_need_verification'] = $attribute->_need_verification;
1752
		$input_def['required'] = $attribute->is_required;
1753
		$input_def['frontend_verification'] = $attribute->frontend_verification;
1754
		$input_def['data_type'] = $attribute->data_type;
1755
		$input_def['data_type_to_use'] = $attribute->data_type_to_use;
1756
		$input_def['backend_type'] = $attribute->backend_input;
1757
		$input_def['frontend_type'] = $attribute->frontend_input;
1758
		$input_def['is_used_in_quick_add_form'] = $attribute->is_used_in_quick_add_form;
1759
1760
		if ( !empty($attribute_value) && !is_object($attribute_value) ) {
1761
			$input_def['value'] = $attribute_value;
1762
		}
1763
		else if ( !empty($attribute_value->value) ) {
1764
			$input_def['value'] = stripslashes($attribute_value->value);
1765
		}
1766
		else if ( !empty($specific_argument['element_identifier']) && empty($attribute_value) && (get_post_status($specific_argument['element_identifier']) != 'auto-draft') ) {
1767
			$input_def['value'] = '';
1768
		}
1769
1770
		$input_def['options'] = '';
1771
		$input_more_class = !empty($specific_argument['input_class']) ? $specific_argument['input_class'] : '';
1772
		if ($attribute->data_type == 'datetime') {
1773
			$date_config = unserialize( $attribute->default_value );
1774
			if ((($date_config['default_value'] == '') || ($date_config['default_value'] == 'date_of_current_day')) && ($date_config['default_value'] == 'date_of_current_day')) {
1775
				$input_def['value'] = date('Y-m-d');
1776
			}
1777
			else {
1778
				/**	Modification due to a message on eoxia forum: http://www.eoxia.com/forums/topic/bug-attribut-de-type-date-dans-fiche-produit-admin/	*/
1779
				$input_def['value'] = !empty($attribute_value->value) && is_string($attribute_value->value) ? str_replace( " 00:00:00", "", $attribute_value->value ) : ( !empty($attribute_value) && is_string($attribute_value) ? str_replace( " 00:00:00", "", $attribute_value ) : '' );
1780
			}
1781
			$input_more_class .= ' wpshop_input_datetime ';
1782
			$field_script = '<script type="text/javascript" >
1783
	jQuery(document).ready(function(){
1784
		wpshop("#' . $input_def['id'] . '").datepicker();
1785
		wpshop("#' . $input_def['id'] . '").datepicker("option", "dateFormat", "yy-mm-dd");
1786
		wpshop("#' . $input_def['id'] . '").datepicker("option", "changeMonth", true);
1787
		wpshop("#' . $input_def['id'] . '").datepicker("option", "changeYear", true);
1788
		wpshop("#' . $input_def['id'] . '").datepicker("option", "yearRange", "-90:+10");
1789
		wpshop("#' . $input_def['id'] . '").datepicker("option", "navigationAsDateFormat", true);
1790
		wpshop("#' . $input_def['id'] . '").val("' . str_replace(" 00:00:00", "", $input_def['value']) . '");';
1791
1792
			if ( !empty($date_config['field_options']['attribute_type_date_options_available_date_past_futur']) ) {
1793 View Code Duplication
				if ( !empty($date_config['field_options']['attribute_type_date_options_available_date_past_futur']['minDate'][0]) ) {
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...
1794
					$field_script .= '
1795
		wpshop("#' . $input_def['id'] . '").datepicker("option", "minDate", "' . $date_config['field_options']['attribute_type_date_options_available_date_past_futur']['minDate'][0] . '");';
1796
				}
1797 View Code Duplication
				if ( !empty($date_config['field_options']['attribute_type_date_options_available_date_past_futur']['maxDate'][0]) ) {
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...
1798
					$field_script .= '
1799
		wpshop("#' . $input_def['id'] . '").datepicker("option", "maxDate", "' . $date_config['field_options']['attribute_type_date_options_available_date_past_futur']['maxDate'][0] . '");';
1800
				}
1801
			}
1802
1803
			$script_options = $script_options_params = array();
1804
			if ( !empty($date_config['field_options']['attribute_type_date_options_day_to_show']) ) {
1805
				$day_to_show_list = '    ';
1806
				foreach ( $date_config['field_options']['attribute_type_date_options_day_to_show'] as $day_to_show ) {
1807
					$day_to_show_list .= '(date.getDay() == ' . $day_to_show . ') || ';
1808
				}
1809
				$script_options[] = '( ' . substr($day_to_show_list, 0, -4) . ' )';
1810
			}
1811
1812
			if ( !empty($date_config['field_options']['attribute_type_date_options_available_date_type'][0]) ) {
1813
				if ( !empty($date_config['field_options']['attribute_type_date_options_available_date']) ) {
1814
					$available_date = ' ';
1815
					foreach ( $date_config['field_options']['attribute_type_date_options_available_date'] as $avalaible_date_list ) {
1816
						if ( !empty($avalaible_date_list) ) {
1817
							$available_date .= '"' . $avalaible_date_list . '",';
1818
						}
1819
					}
1820
					$script_options_params[] = 'var dates = [' . substr($available_date, 0, -1) . ']';
1821
					$script_options[] = '(jQuery.inArray(dmy, dates) ' . ($date_config['field_options']['attribute_type_date_options_available_date_type'][0] == 'available' ? '!=' : '==') . ' -1)';
1822
				}
1823
			}
1824
1825
			if ( !empty( $script_options ) ) {
1826
				$field_script .= '
1827
		wpshop("#' . $input_def['id'] . '").datepicker("option", "beforeShowDay", function(date){
1828
			' . implode(' ', $script_options_params) . ';
1829
			var Y = date.getFullYear();
1830
			var M = (date.getMonth()+1);
1831
			if( M < 10) {
1832
				M = "0" + M;
1833
			}
1834
			var D = date.getDate();
1835
			if( D < 10) {
1836
				D = "0" + D;
1837
			}
1838
			dmy = Y + "-" + M + "-" + D;
1839
			if ( ' . implode(' && ', $script_options) . ' ) {
1840
				return [true, ""];
1841
		  	}
1842
			else {
1843
		   		return [false,""];
1844
		  	}
1845
		});';
1846
			}
1847
1848
			$field_script .= '
1849
	});
1850
</script>';
1851
			$input_def['options'] .= $field_script;
1852
		}
1853
		if ( in_array($attribute->backend_input, array('multiple-select', 'select', 'radio', 'checkbox'))) {
1854
			$input_more_class .= (!empty($specific_argument['no_chosen']) ? '' : ' chosen_select ' );
1855
			$input_def['type'] = ((!empty($specific_argument['from']) && ($specific_argument['from'] == 'frontend')) || (!is_admin() && empty($specific_argument['from'])) ? $attribute->frontend_input : $attribute->backend_input);
1856
			$input_def['valueToPut'] = 'index';
1857
1858
			$select_display = self::get_select_output($attribute, $specific_argument);
1859
			if ( empty( $input_def[ 'options_label' ] ) && !empty( $specific_argument ) && (!empty($specific_argument['from']) && ($specific_argument['from'] == 'frontend') ) ) {
1860
				$input_def[ 'options_label' ][ 'original' ] = true;
1861
			}
1862
			$input_def['options'] .= $select_display['more_input'];
1863
			$input_def['possible_value'] = (!empty($select_display) && !empty($select_display['possible_value'])) ? $select_display['possible_value'] : '';
1864
			if ( !is_admin() ) {
1865
				$input_def['options'] .= '<input type="hidden" value="' . str_replace("\\", "", $input_def['value']) . '" name="wpshop_product_attribute_' . $attribute->code . '_current_value" id="wpshop_product_attribute_' . $attribute->code . '_current_value" />';
1866
			}
1867
			if ( in_array($attribute->backend_input, array('multiple-select', 'checkbox')) && is_admin() && (empty($specific_argument['from']) || ($specific_argument['from'] != 'frontend')) ) {
1868
				$input_def['options'] .= wpshop_display::display_template_element('select_list_multiple_bulk_action', array( 'CURRENT_ATTRIBUTE_ID' => $input_def['id'], 'CURRENT_ATTRIBUTE_CODE' => $attribute->code), array(), 'admin');
1869
			}
1870
		}
1871
		$input_def['label_pointer'] = 'for="' . $input_def['id'] . '"';
1872
		if(($input_def['type'] == 'radio') || ($input_def['type'] == 'checkbox')){
1873
			$input_def['label_pointer'] = '';
1874
		}
1875
1876
		/*
1877
		 * Specifc treatment for price attributes
1878
		 */
1879
		if((WPSHOP_PRODUCT_PRICE_PILOT == 'HT') && ($attribute->code == WPSHOP_PRODUCT_PRICE_TTC) ){
1880
			$input_def['option'] .= ' readonly="readonly" ';
1881
			$input_more_class .= ' wpshop_prices_readonly';
1882
		}
1883
		elseif((WPSHOP_PRODUCT_PRICE_PILOT == 'TTC') && ($attribute->code == WPSHOP_PRODUCT_PRICE_HT) ){
1884
			$input_def['option'] .= ' readonly="readonly" ';
1885
			$input_more_class .= ' wpshop_prices_readonly';
1886
		}
1887
		if ($attribute->code == WPSHOP_PRODUCT_PRICE_TAX_AMOUNT) {
1888
			$input_def['option'] .= ' readonly="readonly" ';
1889
			$input_more_class .= ' wpshop_prices_readonly';
1890
		}
1891
1892
		$input_def['label'] = str_replace("\\", "", $input_def['label']);
1893
// 		$input_def['value'] = str_replace("\\", "", $input_def['value']);
0 ignored issues
show
Unused Code Comprehensibility introduced by
69% 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...
1894
		$input_def['option'] .= ' class="wpshop_product_attribute_' . $attribute->code . $input_more_class . ' ' . (( is_admin() ) ? $attribute->backend_css_class : $attribute->frontend_css_class) . ( !empty($attribute->frontend_verification) ? ' wps_attr_verification_' . $attribute->frontend_verification : '' ) . '" ';
1895
		$input_def['title'] = !empty($attribute->frontend_help_message) ? ' title="' . $attribute->frontend_help_message . '" ' : '';
1896
1897
		if (($attribute->is_intrinsic == 'yes') && ((!empty($input_def['value'])) || ($input_def['value'] > 0))) {
1898
			$input_def['option'] .= ' readonly="readonly" ';
1899
		}
1900
1901
		/*
1902
		 * Add the unit to the attribute if attribute configuration is set to yes
1903
		 */
1904
		if ($attribute->is_requiring_unit == 'yes') {
1905
			if ( in_array($attribute->code, $wpshop_price_attributes) || ( WPSHOP_COST_OF_POSTAGE == $attribute->code) ) {
1906
				$input_def['options'] .= '&nbsp;<span class="attribute_currency" id="attribute_currency_' . $attribute->id . '" >' . wpshop_tools::wpshop_get_currency() . '</span>';
1907
			}
1908
			elseif ( in_array($attribute->code, $wpshop_weight_attributes) ) {
1909
				$weight_defaut_unity_option = get_option('wpshop_shop_default_weight_unity');
1910
				$query = $wpdb->prepare('SELECT name FROM '. WPSHOP_DBT_ATTRIBUTE_UNIT . ' WHERE id=%d', $weight_defaut_unity_option);
1911
				$unity = $wpdb->get_var( $query );
1912
				$input_def['options'] .= '&nbsp;<span class="attribute_weight" id="attribute_weight_' . $attribute->id . '" >' . __($unity, 'wpshop') . '</span>';
1913
			}
1914
			else {
1915
				unset($unit_input_def);
1916
				$unit_input_def['possible_value'] = wpshop_attributes_unit::get_unit_list_for_group($attribute->_unit_group_id);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$unit_input_def was never initialized. Although not strictly required by PHP, it is generally a good practice to add $unit_input_def = 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...
1917
				$unit_input_def['type'] = 'select';
1918
				$unit_input_def['option'] = ' class="wpshop_attribute_unit_input chosen_select" ';
1919
				$unit_input_def['id'] = ( !empty($specific_argument['page_code']) ? $specific_argument['page_code'] : null ) . '_' . ( !empty($specific_argument['element_identifier']) ? $specific_argument['element_identifier'] : null ) . '_unit_attribute_' . $attribute->id;
1920
				$unit_input_def['name'] = $attribute->code;
1921
				$unit_input_def['value'] = (!empty($attribute_value->unit_id) ? $attribute_value->unit_id : '');
1922
				if($unit_input_def['value'] == ''){
1923
					if ( $attribute->_default_unit > 0 ) {
1924
						$unit_input_def['value'] = $attribute->_default_unit;
1925
					}
1926
					else {
1927
						$unit_input_def['value'] = wpshop_attributes_unit::get_default_unit_for_group($attribute->_unit_group_id);
1928
					}
1929
				}
1930
				$input_def['options'] .= wpshop_form::check_input_type($unit_input_def, $attributeInputDomain . '[unit]');
1931
			}
1932
		}
1933
1934
		/*
1935
		 * Add indication on postage cost tax
1936
		 */
1937
		if ( $attribute->code == WPSHOP_COST_OF_POSTAGE ) {
1938
			$input_def['options'] .= ' <span class="attribute_currency" >' . __('ATI', 'wpshop') . '</span>';
1939
		}
1940
1941
		/*
1942
		 * Create the field output
1943
		 */
1944
		if ( is_admin() && ($attribute->data_type == 'datetime') && ($attribute->is_user_defined == 'yes') && (empty($specific_argument['from']) || ($specific_argument['from'] != 'frontend')) ) {
1945
			$input_def['output'] = sprintf(__('You select this field to be defined by final customer into frontend part. To change this behaviour you have to change attribute option "%s"', 'wpshop'),__('is_user_defined', 'wpshop'));
1946
			$input_def['options'] = '';
1947
			$input_def['label_pointer'] = '';
1948
			$input_def['option'] = substr( $input_def['option'], 0 , -2 ) . ' wpshop_attributes_is_user_defined_admin_field "';
1949
			$input_def['field_container_class'] .= 'wpshop_attributes_is_user_defined_admin_container';
1950
		}
1951
		else {
1952
			$input_def['output'] = wpshop_form::check_input_type($input_def, $attributeInputDomain);
1953
		}
1954
		return $input_def;
1955
	}
1956
1957
	/**
1958
	 *
1959
	 * @param array $attribute_list
0 ignored issues
show
Bug introduced by
There is no parameter named $attribute_list. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

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

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

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

Loading history...
1960
	 * @param string $output_from
1961
	 * @return string The output for
1962
	 */
1963
	public static function display_attribute( $attribute_code, $output_from = 'admin', $output_specs = array() ) {
1964
		$output = '';
1965
		/*	Get the page code	*/
1966
		$currentPageCode = !empty($output_specs['page_code']) ? $output_specs['page_code'] : '';
1967
		$element_identifier = !empty($output_specs['element_identifier']) ? $output_specs['element_identifier'] : '';
1968
1969
		/*	Get attribute definition	*/
1970
		$attribute_def = wpshop_attributes::getElement($attribute_code, "'valid'", 'code');
1971
1972
		/*	Get attribute input definition	*/
1973
		$current_value = (!empty($output_specs['current_value']) ? $output_specs['current_value'] : '');
1974
		$input = wpshop_attributes::get_attribute_field_definition( $attribute_def, $current_value, array_merge($output_specs, array('input_class' => ' wpshop_attributes_display', 'from' => $output_from)) );
1975
1976
		/*	Create default output	*/
1977
		$input_to_display = $input['output'] . $input['options'];
1978
1979
		/*	Check if current field is linked to an addon, and if the addon is activated	*/
1980
		$addons_list = unserialize(WPSHOP_ADDONS_LIST);
1981
		foreach ( $addons_list as $addon_code => $addon_def ) {
1982
			if ( in_array($attribute_code, $addon_def) ) {
1983
				if ( constant($addon_code) === false ) {
1984
					$input_to_display = '<a href="' . admin_url('options-general.php?page=wpshop_option#wpshop_addons_option') . '" >' . __("This addon isn't activated, click to activate",'wpshop') . '</a>';
1985
				}
1986
			}
1987
		}
1988
1989
		/*	Check the prices attribute because output for this attributes is customized	*/
1990
		$price_tab = unserialize(WPSHOP_ATTRIBUTE_PRICES);
1991
		unset($price_tab[array_search(WPSHOP_COST_OF_POSTAGE, $price_tab)]);
1992
1993
 		$output['field'] = '
1994
<div class="wpshop_cls" >
1995
	<div class="wpshop_form_label ' . $currentPageCode . '_' . $input['name'] . '_label ' . (in_array($attribute_def->code, $price_tab) ? $currentPageCode . '_prices_label ' : '') . ' alignleft" >
1996
		<label ' . $input['label_pointer'] . ' >' . __($input['label'], 'wpshop') . ($attribute_def->is_required == 'yes' ? ' <span class="wpshop_required" >*</span>' : '') . '</label>
1997
	</div>
1998
	<div class="wpshop_form_input_element ' . $currentPageCode . '_' . $input['name'] . '_input ' . (in_array($attribute_def->code, $price_tab) ? $currentPageCode . '_prices_input ' : '') . ' ' . $input['field_container_class'] . ' alignleft" >
1999
		' . $input_to_display . '
2000
	</div>';
2001
2002
// 		$output['field']  = '<div class="wps-form-group wpshop_form_label ' . $currentPageCode . '_' . $input['name'] . '_label ' . (in_array($attribute_def->code, $price_tab) ? $currentPageCode . '_prices_label ' : '') . ' ">';
0 ignored issues
show
Unused Code Comprehensibility introduced by
47% 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...
2003
// 		$output['field'] .= '<label ' . $input['label_pointer'] . '>' . __($input['label'], 'wpshop'). '</label>'.( ($attribute_def->is_required == 'yes') ? '<span class="wps-help-inline wps-help-inline-title">' .__( 'Required variation', 'wpshop' ). '</span>' : '');
2004
// 		$output['field'] .= '<div class="wps-form ' . $currentPageCode . '_' . $input['name'] . '_input ' . (in_array($attribute_def->code, $price_tab) ? $currentPageCode . '_prices_input ' : '') . ' ' . $input['field_container_class'] . ' ">' .$input_to_display. '</div>';
2005
2006
		/*
2007
		 * Display attribute option if applicable
2008
		 */
2009 View Code Duplication
		if ( $output_from == 'admin') {
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...
2010
			$attribute_option_display = $attribute_def->backend_input=='select' && (strtolower( __(self::get_attribute_type_select_option_info($input['value'], 'value'), 'wpshop') ) == strtolower(__('yes', 'wpshop'))) ? '' : ' wpshopHide';
2011
2012
			$output['field'] .= '
2013
	<div class="attribute_option_'.$attribute_def->code.''.$attribute_option_display.'">'.self::get_attribute_option_fields($element_identifier, $attribute_def->code).'</div>';
2014
		}
2015
2016
		$output['field'] .= '</div>';
2017
		$output['field_definition'] = $input;
2018
2019
		return $output;
2020
	}
2021
2022
	/**
2023
	 * Output the different tabs into an entity sheet
2024
	 *
2025
	 * @param string $element_code The current element type represented by the code
2026
	 * @param integer $element_id The current element identifier to dislay tabs for
2027
	 * @param array $element_definition An array with the different configuration for the current element
2028
	 *
2029
	 * @return string The html code to output directly tabs
2030
	 */
2031
	public static function attribute_of_entity_to_tab( $element_code, $element_id, $element_definition ) {
2032
		$attributeContentOutput = '';
2033
2034
		/**	Get the different attribute affected to the entity	*/
2035
		$element_atribute_list = wpshop_attributes::getElementWithAttributeAndValue($element_code, $element_id, WPSHOP_CURRENT_LOCALE, '', 'frontend');
2036
2037
2038
		if ( is_array($element_atribute_list) && (count($element_atribute_list) > 0) ) {
2039
			foreach ( $element_atribute_list[$element_id] as $attributeSetSectionName => $attributeSetContent ) {
2040
				$attributeToShowNumber = 0;
2041
				$attributeOutput = '';
2042
2043
				foreach ( $attributeSetContent['attributes'] as $attributeId => $attributeDefinition ) {
2044
2045
					/**	Check the value type to check if empty or not	*/
2046
					if ( $attributeDefinition['data_type'] == 'int' ) {
2047
						$attributeDefinition['value'] = (int)$attributeDefinition['value'];
2048
					}
2049
					else if ( $attributeDefinition['data_type'] == 'decimal' ) {
2050
						$attributeDefinition['value'] = (float)$attributeDefinition['value'];
2051
					}
2052
2053
					/** Check if the attribute is set to be displayed in frontend	*/
2054
					$attribute_display_state = wpshop_attributes::check_attribute_display( $attributeDefinition['is_visible_in_front'], $element_definition['custom_display'], 'attribute', $attributeDefinition['code'], 'complete_sheet');
2055
2056
					/**	Output the field if the value is not null	*/
2057
2058
					if ( (is_array($attributeDefinition['value']) || ( !empty($attributeDefinition['value']) ) ) && $attribute_display_state) {
2059
2060
						$attribute_display = wpshop_attributes::wps_attribute_values_display( $attributeDefinition );
2061
						$attribute_value = $attribute_display[0];
2062
						$attributeDefinition['value'] = $attribute_display[1];
2063
						$attribute_unit_list = $attribute_display[2];
2064
2065
						/** Template parameters	*/
2066
						$template_part = 'product_attribute_display';
2067
						$tpl_component = array();
2068
						$tpl_component['PDT_ENTITY_CODE'] = self::currentPageCode;
2069
						$tpl_component['ATTRIBUTE_CODE'] = $attributeDefinition['attribute_code'];
2070
						$tpl_component['ATTRIBUTE_LABEL'] = __($attributeDefinition['frontend_label'], 'wpshop');
2071
						$tpl_component['ATTRIBUTE_VALUE'] = (  !is_array($attribute_value) ) ? stripslashes($attribute_value) : $attribute_value;
2072
						$tpl_component['ATTRIBUTE_VALUE_UNIT'] =  $attribute_unit_list;
2073
2074
						/** Build template	*/
2075
						$attributeOutput .= wpshop_display::display_template_element($template_part, $tpl_component);
2076
						unset($tpl_component);
2077
2078
						$attributeToShowNumber++;
2079
					}
2080
				}
2081
2082
				/** Check if the attribute set section is set to be displayed in frontend	*/
2083
				$attribute_set_display_state = wpshop_attributes::check_attribute_display( $attributeSetContent['display_on_frontend'], $element_definition['custom_display'], 'attribute_set_section', $attributeSetContent['code'], 'complete_sheet');
2084
2085
				if ( !$attribute_set_display_state ) {
2086
					$attributeToShowNumber = 0;
2087
					$attributeOutput = '';
2088
				}
2089
				$element_atribute_list[$element_id][$attributeSetSectionName]['count'] = $attributeToShowNumber;
2090
				$element_atribute_list[$element_id][$attributeSetSectionName]['output'] = $attributeOutput;
2091
			}
2092
2093
			/** Gestion de l'affichage	*/
2094
			$tab_list = $content_list = '';
2095
			foreach ( $element_atribute_list[$element_id] as $attributeSetSectionName => $attributeSetContent ) {
2096
				if ( !empty($attributeSetContent['count']) > 0 ) {
2097
					/** Template parameters	*/
2098
					$template_part = 'product_attribute_tabs';
2099
					$tpl_component = array();
2100
					$tpl_component['ATTRIBUTE_SET_CODE'] = $attributeSetContent['code'];
2101
					$tpl_component['ATTRIBUTE_SET_NAME'] = __($attributeSetSectionName, 'wpshop');
2102
2103
					/** Build template	*/
2104
					$tpl_way_to_take = wpshop_display::check_way_for_template($template_part);
2105
					if ( $tpl_way_to_take[0] && !empty($tpl_way_to_take[1]) ) {
2106
						/*	Include the old way template part	*/
2107
						ob_start();
2108
						require(wpshop_display::get_template_file($tpl_way_to_take[1]));
2109
						$tab_list .= ob_get_contents();
2110
						ob_end_clean();
2111
					}
2112
					else {
2113
						$tab_list .= wpshop_display::display_template_element($template_part, $tpl_component);
2114
					}
2115
					unset($tpl_component);
2116
2117
					/** Template parameters	*/
2118
					$template_part = 'product_attribute_tabs_detail';
2119
					$tpl_component = array();
2120
					$tpl_component['ATTRIBUTE_SET_CODE'] = $attributeSetContent['code'];
2121
					$tpl_component['ATTRIBUTE_SET_CONTENT'] = $attributeSetContent['output'];
2122
2123
					/** Build template	*/
2124
					$tpl_way_to_take = wpshop_display::check_way_for_template($template_part);
2125
					if ( $tpl_way_to_take[0] && !empty($tpl_way_to_take[1]) ) {
2126
						/*	Include the old way template part	*/
2127
						ob_start();
2128
						require(wpshop_display::get_template_file($tpl_way_to_take[1]));
2129
						$content_list .= ob_get_contents();
2130
						ob_end_clean();
2131
					}
2132
					else {
2133
						$content_list .= wpshop_display::display_template_element($template_part, $tpl_component);
2134
					}
2135
					unset($tpl_component);
2136
				}
2137
			}
2138
2139
			if ( $tab_list != '' ) {
2140
				/** Template parameters	*/
2141
				$template_part = 'product_attribute_container';
2142
				$tpl_component = array();
2143
				$tpl_component['PDT_TABS'] = apply_filters( 'wpshop_extra_tabs_menu_before', '' ).$tab_list.apply_filters( 'wpshop_extra_tabs_menu_after', '' );
2144
				$tpl_component['PDT_TAB_DETAIL'] = apply_filters( 'wpshop_extra_tabs_content_before', '' ).$content_list.apply_filters( 'wpshop_extra_tabs_content_after', '' );
2145
2146
				/** Build template	*/
2147
				$tpl_way_to_take = wpshop_display::check_way_for_template($template_part);
2148
				if ( $tpl_way_to_take[0] && !empty($tpl_way_to_take[1]) ) {
2149
					/*	Include the old way template part	*/
2150
					ob_start();
2151
					require(wpshop_display::get_template_file($tpl_way_to_take[1]));
2152
					$attributeContentOutput = ob_get_contents();
2153
					ob_end_clean();
2154
				}
2155
				else {
2156
					$attributeContentOutput = wpshop_display::display_template_element($template_part, $tpl_component);
2157
				}
2158
				unset($tpl_component);
2159
			}
2160
		}
2161
2162
		return $attributeContentOutput;
2163
	}
2164
2165
	/**
2166
	 * Display value for a given attribute
2167
	 *
2168
	 * @param unknown_type $attributeDefinition
2169
	 * @return multitype:Ambigous <unknown, string> Ambigous <string, string> Ambigous <>
0 ignored issues
show
Documentation introduced by
The doc-type multitype:Ambigous could not be parsed: Unknown type name "multitype:Ambigous" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
2170
	 */
2171
	public static function wps_attribute_values_display( $attributeDefinition ) {
2172
		$attribute_unit_list = '';
2173
		if ( !empty($attributeDefinition['unit']) ) {
2174
			/** Template parameters	*/
2175
			$template_part = 'product_attribute_unit';
2176
			$tpl_component = array();
2177
			$tpl_component['ATTRIBUTE_UNIT'] = $attributeDefinition['unit'];
2178
2179
			/** Build template	*/
2180
			$attribute_unit_list = wpshop_display::display_template_element($template_part, $tpl_component);
2181
			unset($tpl_component);
2182
		}
2183
2184
		$attribute_value = $attributeDefinition['value'];
2185
		if ( $attributeDefinition['data_type'] == 'decimal' ) {
2186
			$attribute_value =(is_numeric($attribute_value) ) ? number_format($attribute_value, 2, ',', '') : $attribute_value;
2187
			if ( in_array($attributeDefinition['code'], unserialize(WPSHOP_ATTRIBUTE_PRICES)) ) {
2188
				if ( $attributeDefinition['is_requiring_unit'] == 'yes' ) {
2189
					$attribute_unit_list = ' ' . wpshop_tools::wpshop_get_currency();
2190
				}
2191
				$attributeDefinition['value'] = wpshop_display::format_field_output('wpshop_product_price', $attributeDefinition['value']);
2192
			}
2193
		}
2194
		if ( $attributeDefinition['data_type'] == 'datetime' ) {
2195
			$attribute_value = mysql2date('d/m/Y', $attributeDefinition['value'], true);
2196
		}
2197
		if ( $attributeDefinition['backend_input'] == 'select' ) {
2198
			$attribute_value = wpshop_attributes::get_attribute_type_select_option_info($attributeDefinition['value'], 'label', $attributeDefinition['data_type_to_use']);
2199
		}
2200
		/** Manage differently if its an array of values or not	*/
2201
		if ( $attributeDefinition['backend_input'] == 'multiple-select') {
2202
			$attribute_value = '';
2203
			if ( is_array($attributeDefinition['value']) ) {
2204
				foreach ($attributeDefinition['value'] as $v) {
2205
					$attribute_value .= ' / '.wpshop_attributes::get_attribute_type_select_option_info($v, 'label', $attributeDefinition['data_type_to_use']);
2206
				}
2207
			}
2208
			else $attribute_value = ' / '.wpshop_attributes::get_attribute_type_select_option_info($attributeDefinition['value'], 'label', $attributeDefinition['data_type_to_use']);
2209
			$attribute_value = substr($attribute_value,3);
2210
		}
2211
2212
		return array($attribute_value, $attributeDefinition['value'], $attribute_unit_list);
2213
	}
2214
2215
	/**
2216
	 * Manage display for the output when user uses a shortcode for attributes display
2217
	 * @param array $shorcode_args The list of argument passed through the shortcode
2218
	 */
2219
	function wpshop_attributes_shortcode( $shorcode_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...
2220
		$output = '';
2221
		/*
2222
		 * Read the attribute list
2223
		*/
2224
		foreach ( explode(', ', $shorcode_args['attributes']) as $attribute_code ) {
2225
			$attribute_output_def = wpshop_attributes::display_attribute( $attribute_code, $shorcode_args['from'] );
2226
			$output .= $attribute_output_def['field'];
2227
		}
2228
2229
		return $output;
2230
	}
2231
2232
	/**
2233
	 *
2234
	 * @param unknown_type $attributeSetId
2235
	 * @param unknown_type $currentPageCode
2236
	 * @param unknown_type $itemToEdit
2237
	 * @param unknown_type $outputType
2238
	 * @return Ambigous <multitype:, string>
2239
	 */
2240
	public static function entities_attribute_box($attributeSetId, $currentPageCode, $itemToEdit, $outputType = 'box') {
2241
		$box = $box['box'] = $box['boxContent'] = $box['generalTabContent'] = array();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$box was never initialized. Although not strictly required by PHP, it is generally a good practice to add $box = 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...
2242
		$box['boxMore'] = '';
2243
		/*	Get the attribute set details in order to build the product interface	*/
2244
		$productAttributeSetDetails = wpshop_attributes_set::getAttributeSetDetails($attributeSetId, "'valid','deleted'");
2245
		$attribute_specification = array('page_code' => $currentPageCode, 'element_identifier' => $itemToEdit, 'field_id' => $currentPageCode . '_' . $itemToEdit . '_');
2246
2247
		if ( count($productAttributeSetDetails) > 0 ) {
2248
			/*	Read the attribute list in order to output	*/
2249
			$shortcodes_attr = '';
2250
			$shortcodes_to_display = false;
2251
			$attribute_set_id_is_present = false;
2252
2253
			foreach ($productAttributeSetDetails as $productAttributeSetDetail) {
0 ignored issues
show
Bug introduced by
The expression $productAttributeSetDetails of type string is not traversable.
Loading history...
2254
2255
				$shortcodes = $currentTabContent = '';
2256
				$output_nb = 0;
2257
				if(count($productAttributeSetDetail['attribut']) >= 1){
2258
					foreach($productAttributeSetDetail['attribut'] as $attribute){
2259
2260
						if ( !empty($attribute->id) ) {
2261
							if ( $attribute->code == 'product_attribute_set_id' ) {
2262
								$attribute_set_id_is_present = true;
2263
							}
2264
2265
							/** Generic part for attribute field output	*/
2266
							$value = wpshop_attributes::getAttributeValueForEntityInSet($attribute->data_type, $attribute->id, wpshop_entities::get_entity_identifier_from_code($currentPageCode), $itemToEdit, array('intrinsic' => $attribute->is_intrinsic, 'backend_input' => $attribute->backend_input));
2267
							$product_meta = get_post_meta( $itemToEdit, '_wpshop_product_metadata', true);
2268
2269
							/**	Check if value is empty and get value in meta if not empty	*/
2270
							$value = (empty($value) && !empty($product_meta[$attribute->code])) ? $product_meta[$attribute->code] : (!empty($value) ? $value : null);
2271
2272
							/*	Manage specific field as the attribute_set_id in product form	*/
2273
							if ( $attribute->code == 'product_attribute_set_id' ) {
2274
2275
								$value = empty($value) ? $attributeSetId : $value;
2276
							}
2277
							$attribute_specification['current_value'] = $value;
2278
							$attribute_output_def = apply_filters( 'wpshop_attribute_output_def', wpshop_attributes::display_attribute( $attribute->code, 'admin', $attribute_specification), $itemToEdit );
2279
							if ( ($attribute_output_def['field_definition']['type'] != 'hidden') && ($attribute->code != 'product_attribute_set_id') ) {
2280
								$currentTabContent .= $attribute_output_def['field'];
2281
								$shortcode_code_def=array();
2282
								$shortcode_code_def['attribute_'.str_replace('-', '_', sanitize_title($attribute_output_def['field_definition']['label']))]['main_code'] = 'wpshop_att_val';
2283
								$shortcode_code_def['attribute_'.str_replace('-', '_', sanitize_title($attribute_output_def['field_definition']['label']))]['attrs_exemple']['type'] = $attribute->data_type;
2284
								$shortcode_code_def['attribute_'.str_replace('-', '_', sanitize_title($attribute_output_def['field_definition']['label']))]['attrs_exemple']['attid'] = $attribute->id;
2285
								$shortcode_code_def['attribute_'.str_replace('-', '_', sanitize_title($attribute_output_def['field_definition']['label']))]['attrs_exemple']['pid'] = $itemToEdit;
2286
								ob_start();
2287
								wps_shortcodes_ctr::output_shortcode('attribute_'.str_replace('-', '_', sanitize_title($attribute_output_def['field_definition']['label'])), $shortcode_code_def, 'wpshop_product_shortcode_display wpshop_product_attribute_shortcode_display wpshop_product_attribute_shortcode_display_'.str_replace('-', '_', sanitize_title($attribute_output_def['field_definition']['label'])).' wpshop_cls');
0 ignored issues
show
Documentation introduced by
$shortcode_code_def is of type array, but the function expects a string.

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...
2288
								$shortcodes .= '<li class="wpshop_cls" >'.sprintf(__('Insertion code for the attribute %s for this product', 'wpshop'), '<span>'.__($attribute_output_def['field_definition']['label'], 'wpshop').'</span>').ob_get_contents().'</li>';
2289
								ob_end_clean();
2290
							}
2291
							else {
2292
								if ( $attribute->code == 'product_attribute_set_id' ) {
2293
									$attribute_output_def['field_definition']['type'] = 'hidden';
2294
								}
2295
								$currentTabContent .=  wpshop_form::check_input_type($attribute_output_def['field_definition'], $attribute_output_def['field_definition']['input_domain']);
2296
							}
2297
							$output_nb++;
2298
						}
2299
					}
2300
2301
					$currentTabContent = apply_filters( 'wps_entity_attribute_edition', $currentTabContent, $itemToEdit, $productAttributeSetDetail );
2302
2303
					$shortcode_code['attributes_set']['main_code'] = 'wpshop_att_group';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$shortcode_code was never initialized. Although not strictly required by PHP, it is generally a good practice to add $shortcode_code = 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...
2304
					$shortcode_code['attributes_set']['attrs_exemple']['pid'] = $itemToEdit;
0 ignored issues
show
Bug introduced by
The variable $shortcode_code 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...
2305
					$shortcode_code['attributes_set']['attrs_exemple']['sid'] = $productAttributeSetDetail['id'];
2306
					ob_start();
2307
					wps_shortcodes_ctr::output_shortcode('attributes_set', $shortcode_code, 'wpshop_product_shortcode_display wpshop_product_attribute_group_shortcode_display wpshop_product_attribute_group_shortcode_display_'.str_replace('-', '_', sanitize_title($productAttributeSetDetail['name'])).' cls');
2308
					$attribute_group_display = sprintf(__('Insertion code for attribute group %s for this product', 'wpshop'), '<span>'.$productAttributeSetDetail['name'].'</span>').ob_get_contents().'<ul class="" >'.$shortcodes.'</ul>';
2309
					ob_end_clean();
2310
2311
					if( WPSHOP_PRODUCT_SHORTCODE_DISPLAY_TYPE == 'each-box' )
2312
						$currentTabContent .= '<div class="wpshop_cls" ><strong>'.__('Shortcodes','wpshop').'</strong> - <a href="#" class="show-hide-shortcodes">' . __('Display', 'wpshop') . '</a><div class="wpshop_product_shortcode_display wpshop_product_shortcode_display_container wpshopHide" >' . $attribute_group_display . '</div></div>';
2313
					else
2314
						$shortcodes_attr .= $attribute_group_display;
2315
2316
					if ( $output_nb <= 0 ) {
2317
						$currentTabContent = __('Nothing avaiblable here. You can go in attribute management interface in order to add content here.', 'wpshop');
2318
					}
2319
				}
2320
2321
				if ($output_nb > 0) {
2322
					$shortcodes_to_display = true;
2323
					if ( $outputType == 'box' ) {
2324
						$box['box'][$productAttributeSetDetail['code']] = $productAttributeSetDetail['name'];
2325
						$box['box'][$productAttributeSetDetail['code'].'_backend_display_type'] = $productAttributeSetDetail['backend_display_type'];
2326
						$box['boxContent'][$productAttributeSetDetail['code']] = '
2327
			<div id="wpshop_' . $currentPageCode . '_' . wpshop_tools::slugify($productAttributeSetDetail['code'], array('noAccent')) . '_form" >' . $currentTabContent . '
2328
							</div><div class="wpshop_cls" ></div>';
2329
					}
2330
					else if ( $outputType == 'column' ) {
2331
						$currentTabContent = str_replace('wpshop_form_input_element', 'wpshop_form_input_column', $currentTabContent);
2332
						$currentTabContent = str_replace('wpshop_form_label', 'wpshop_form_label_column', $currentTabContent);
2333
2334
						$box['columnTitle'][$productAttributeSetDetail['code']] = __($productAttributeSetDetail['name'], 'wpshop');
2335
						$box['columnContent'][$productAttributeSetDetail['code']] = $currentTabContent;
2336
					}
2337
				}
2338
			}
2339
2340
			if( !$attribute_set_id_is_present ) {
2341
				/*	Get attribute definition	*/
2342
				$attribute_def = wpshop_attributes::getElement('product_attribute_set_id', "'valid'", 'code');
2343
				/*	Get attribute input definition	*/
2344
				$input = wpshop_attributes::get_attribute_field_definition( $attribute_def, $attributeSetId, array_merge($attribute_specification, array('input_class' => ' wpshop_attributes_display', 'from' => 'admin')) );
2345
				$input['type'] = 'hidden';
2346
2347
				$box['boxMore'] = wpshop_form::check_input_type($input, $input['input_domain']);
2348
			}
2349
2350
			/*	Ajout de la boite permettant d'ajouter des valeurs aux attributs de type liste deroulante a la volee	*/
2351
			$dialog_title = __('New value for attribute', 'wpshop');
2352
			$dialog_identifier = 'wpshop_new_attribute_option_value_add';
2353
			$dialog_input_identifier = 'wpshop_new_attribute_option_value';
2354
			ob_start();
2355
			include(WPSHOP_TEMPLATES_DIR.'admin/add_new_element_dialog.tpl.php');
2356
			$box['boxMore'] .= ob_get_contents();
2357
			ob_end_clean();
2358
			$box['boxMore'] .= '<input type="hidden" name="wpshop_attribute_type_select_code" value="" id="wpshop_attribute_type_select_code" />';
2359
2360
			if ( $shortcodes_to_display ) {
2361
				switch ( WPSHOP_PRODUCT_SHORTCODE_DISPLAY_TYPE ) {
2362
					case 'fixed-tab':
2363
					case 'movable-tab':
2364
						if ($outputType == 'box') {
2365
							$box['box']['shortcode'] = __('Product Shortcodes', 'wpshop');
2366
							$box['boxContent']['shortcode'] = $shortcodes_attr;
2367
							$box['box']['shortcode_backend_display_type'] = WPSHOP_PRODUCT_SHORTCODE_DISPLAY_TYPE;
2368
						}
2369
						else{
2370
							$box['columnTitle']['shortcode'] = __('Product Shortcodes', 'wpshop');
2371
							$box['columnContent']['shortcode'] = $shortcodes_attr;
2372
						}
2373
						break;
2374
				}
2375
			}
2376
		}
2377
2378
		return $box;
2379
	}
2380
2381
	/**
2382
	 * Generate the list of element to put into a combobox
2383
	 *
2384
	 * @param object $attribute Complete definition of attribute to generate output for
2385
	 * @return array The output for the combobox
2386
	 */
2387
	public static function get_select_output($attribute, $provenance = array()) {
2388
		global $wpdb;
2389
		$ouput = array();
2390
		$ouput['more_input'] = '';
2391
2392
		$attribute_default_value = $attribute->default_value;
2393 View Code Duplication
		if ( !empty($attribute->default_value) && ($attribute->default_value == serialize(false) || wpshop_tools::is_serialized( $attribute->default_value ) ) ) {
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...
2394
			$tmp_default_value = unserialize($attribute->default_value);
2395
			$attribute_default_value = !empty($tmp_default_value["default_value"]) ? $tmp_default_value["default_value"] : null;
2396
		}
2397
2398
		if ( $attribute->data_type_to_use == 'custom') {
2399
			$query = $wpdb->prepare("SELECT id, label, value, '' as name FROM " . WPSHOP_DBT_ATTRIBUTE_VALUES_OPTIONS . " WHERE attribute_id = %d AND status = 'valid' ORDER BY position", $attribute->id);
2400
			$attribute_select_options = $wpdb->get_results($query);
2401
2402
			/*	Read existing element list for creating the possible values	*/
2403
			foreach ($attribute_select_options as $index => $option) :
2404
				$attribute_select_options_list[$option->id] = $option->label;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$attribute_select_options_list was never initialized. Although not strictly required by PHP, it is generally a good practice to add $attribute_select_options_list = 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...
2405
// 				if ( is_admin() ) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% 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...
2406
//					$ouput['more_input'] .= '<input type="hidden" value="' . (WPSHOP_DISPLAY_VALUE_FOR_ATTRIBUTE_SELECT ? str_replace("\\", "", $option->value) : str_replace("\\", "", $option->label)) . '" name="wpshop_product_attribute_' . $attribute->code . '_value_' . $option->id . '" id="wpshop_product_attribute_' . $attribute->code . '_value_' . $option->id . '" />';
2407
// 				}
2408
			endforeach;
2409
		}
2410
		elseif ( $attribute->data_type_to_use == 'internal')  {
2411
			switch ($attribute_default_value) {
2412
				case 'users':
2413
					$users = get_users('orderby=nicename');
2414
					foreach($users as $user){
2415
						$attribute_select_options_list[$user->ID] = $user->display_name;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$attribute_select_options_list was never initialized. Although not strictly required by PHP, it is generally a good practice to add $attribute_select_options_list = 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...
2416
					}
2417
				break;
2418
				default:
2419
					wp_reset_query();
2420
					$wpshop_attr_custom_post_query = new WP_Query(array(
2421
						'post_type' => $attribute_default_value,
2422
						'posts_per_page' => -1,
2423
						'post_status' => array( 'publish', 'draft', 'future' ) ,
2424
					));
2425
2426
					if($wpshop_attr_custom_post_query->have_posts()):
2427
						foreach($wpshop_attr_custom_post_query->posts as $post){
2428
							$attribute_select_options_list[$post->ID] = $post->post_title;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$attribute_select_options_list was never initialized. Although not strictly required by PHP, it is generally a good practice to add $attribute_select_options_list = 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...
2429
						}
2430
					endif;
2431
					wp_reset_query();
2432
				break;
2433
			}
2434
		}
2435
2436
		/*	There is no value existing for this value	*/
2437
		if (empty($attribute_select_options_list)) :
2438
			$ouput['more_input'].=__('Nothing found for this field', 'wpshop');
2439
		else:
2440
			/*	Add a default value to the combobox list	*/
2441
			$default_value_is_serial = false;
0 ignored issues
show
Unused Code introduced by
$default_value_is_serial 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...
2442
			$attribute_list_first_element = $attribute->default_value;
0 ignored issues
show
Unused Code introduced by
$attribute_list_first_element 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...
2443 View Code Duplication
			if ( !empty($attribute->default_value) && ($attribute->default_value == serialize(false) || wpshop_tools::is_serialized( $attribute->default_value ) ) ) {
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...
2444
				$default_value_is_serial = true;
0 ignored issues
show
Unused Code introduced by
$default_value_is_serial 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...
2445
				$tmp_default_value = unserialize($attribute->default_value);
2446
				$attribute_list_first_element = $tmp_default_value["field_options"]["label_for_first_item"];
0 ignored issues
show
Unused Code introduced by
$attribute_list_first_element 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...
2447
			}
2448
			//if ( !in_array($attribute->frontend_input, array('radio', 'checkbox')) || ($attribute_list_first_element != 'none') ) $ouput['possible_value'][] = ($default_value_is_serial && !empty($attribute_list_first_element)) ? $attribute_list_first_element : __('Choose a value', 'wpshop');
0 ignored issues
show
Unused Code Comprehensibility introduced by
66% 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...
2449
			foreach ( $attribute_select_options_list as $option_key => $option_value ) {
2450
				$ouput['possible_value'][$option_key] = stripslashes($option_value);
2451
			}
2452
		endif;
2453
2454
		/*	Add a extra element to create a new element into list	*/
2455
		if ( is_admin()  && ( empty($provenance['from']) || ($provenance['from'] != 'frontend')) ) {
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...
2456
			/**	$ouput['more_input'] .= '<img src="'.WPSHOP_MEDIAS_ICON_URL.'add.png" id="new_value_pict_' . $attribute->code . '" alt="'.__('Add a new value for this attribute', 'wpshop').'" title="'.__('Add a new value for this attribute', 'wpshop').'" class="wpshop_icons wpshop_icons_add_new_value_to_option_list wpshop_icons_add_new_value_to_option_list_'.$attribute->code.'" />';	*/
2457
		}
2458
		else if ( 'yes' == $attribute->is_used_in_quick_add_form ) {
2459
			$tpl_component = array();
2460
			$tpl_component['NEW_ELEMENT_CREATION_FIELD'] = 'attribute[new_value_creation][' . $attribute->code . ']';
2461
			$ouput['more_input'] .= wpshop_display::display_template_element('quick_entity_specific_field_new_element', $tpl_component);
2462
		}
2463
2464
		return $ouput;
2465
	}
2466
2467
	public static function get_affected_value_for_list( $attribute_code, $element_id, $attribute_data_type ) {
2468
		global $wpdb;
2469
		$affected_value = array();
2470
2471
		if ( $attribute_data_type == 'custom' ) {
2472
			$query = $wpdb->prepare("
2473
SELECT ATT_SELECT_OPTIONS_VALUE.id AS chosen_val, ATT_SELECT_OPTIONS_VALUE.value
2474
FROM " . WPSHOP_DBT_ATTRIBUTE . " AS ATT
2475
	INNER JOIN " . WPSHOP_DBT_ATTRIBUTE_VALUES_INTEGER . " AS ATT_INT_VAL ON ( (ATT_INT_VAL.attribute_id = ATT.id) AND (ATT_INT_VAL.entity_id = %d) )
2476
	INNER JOIN " . WPSHOP_DBT_ATTRIBUTE_VALUES_OPTIONS . " AS ATT_SELECT_OPTIONS_VALUE ON ( (ATT_SELECT_OPTIONS_VALUE.attribute_id = ATT.id) AND (ATT_SELECT_OPTIONS_VALUE.id = ATT_INT_VAL.value) )
2477
WHERE ATT.code = %s
2478
	AND ATT_SELECT_OPTIONS_VALUE.status = 'valid'
2479
GROUP BY ATT.id, chosen_val", $element_id, $attribute_code);
2480
		}
2481
		else {
2482
			$query = $wpdb->prepare("
2483
SELECT P.ID AS chosen_val, P.post_title
2484
FROM " . WPSHOP_DBT_ATTRIBUTE . " AS ATT
2485
	INNER JOIN " . WPSHOP_DBT_ATTRIBUTE_VALUES_INTEGER . " AS ATT_INT_VAL ON ( (ATT_INT_VAL.attribute_id = ATT.id) AND (ATT_INT_VAL.entity_id = %d) )
2486
	INNER JOIN " . $wpdb->posts . " AS P ON ( P.id = ATT_INT_VAL.value )
2487
WHERE ATT.code = %s
2488
	AND P.post_status = 'publish'
2489
GROUP BY ATT.id, chosen_val", $element_id, $attribute_code);
2490
		}
2491
2492
		$attribute_values_for_variations = $wpdb->get_results($query);
2493
		foreach ( $attribute_values_for_variations as $attribute_def ) {
2494
			$affected_value[] = (int) $attribute_def->chosen_val;
2495
		}
2496
2497
		return $affected_value;
2498
	}
2499
2500
	public static function get_attribute_option_output($item, $attr_code, $attr_option, $additionnal_params = '') {
2501
		switch($attr_code){
2502
			case 'is_downloadable_':
2503
				$option = get_post_meta($item['item_id'], 'attribute_option_'.$attr_code, true);
2504
				switch($attr_option){
2505
					case 'file_url':
2506
						if(in_array($additionnal_params['order_status'], array('completed', 'shipped')) && (!empty($item['item_'.$attr_code]) && (strtolower(__($item['item_'.$attr_code], 'wpshop')) == __('yes','wpshop'))) ){
2507
							$file_url = isset($option[$attr_option]) ? $option[$attr_option] : false;
2508
							return $file_url;
2509
						}
2510
						return false;
2511
						break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
2512
				}
2513
				break;
2514
		}
2515
	}
2516
2517
	public static function get_attribute_option_fields($postid, $code) {
2518
2519
		switch($code){
2520
			case 'is_downloadable_':
2521
				$data = get_post_meta($postid, 'attribute_option_'.$code, true);
2522
				$data['file_url'] = !empty($data['file_url'])?$data['file_url']:__('No file selected', 'wpshop');
2523
				$fields =  wp_nonce_field( 'ajax_wpshop_show_downloadable_interface_in_admin'.$postid, '_show_downloadable_interface_in_admin_wpnonce', true, false );
2524
				$fields .= '<div class="wpshop_form_label alignleft">&nbsp;</div>
2525
						<div class="wpshop_form_input_element alignleft">
2526
						<div class="send_downloadable_file_dialog wpshop_add_box" data-post="'.$postid.'" title="' .__('Send the downloadable file', 'wpshop'). '"></div>
2527
						<a data-nonce="' . wp_create_nonce( "ajax_wpshop_fill_the_downloadable_dialog".$postid ) . '"  class="send_downlodable_file wps-bton-first-mini-rounded">' .__('Send a file', 'wpshop').'</a>
2528
						<input type="hidden" class="product_identifer_field" value="' .( !empty($postid) ? esc_attr( $postid ) : '') . '" /><br/><u>'.__('File url','wpshop').' :</u>
2529
						<div class="is_downloadable_statut_'.$postid.'"><a href="' .$data['file_url']. '" target="_blank" download>'.basename($data['file_url']).'</a></div>
2530
						</div>';
2531
				return $fields;
2532
				break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
2533
2534
			default:
2535
				return '';
2536
				break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
2537
		}
2538
2539
	}
2540
2541
	/**
2542
	 *	Return content informations about a given attribute
2543
	 *
2544
	 *	@param string $attribute_code The code of attribute to get (Not the id because if another system is using eav model it could have some conflict)
2545
	 *	@param integer $entity_id The current entity we want to have the attribute value for
2546
	 *	@param string $entity_type The current entity type code we want to have the attribute value for
2547
	 *
2548
	 *	@return object $attribute_value_content The attribute content
2549
	 */
2550
	public static function get_attribute_value_content($attribute_code, $entity_id, $entity_type) {
2551
		$attribute_value_content = '';
2552
2553
		$atributes = self::getElement($attribute_code, "'valid'", 'code');
2554
		if ( !empty($atributes) ) {
2555
			$attribute_value_content = self::getAttributeValueForEntityInSet($atributes->data_type, $atributes->id,  wpshop_entities::get_entity_identifier_from_code($entity_type), $entity_id);
2556
		}
2557
2558
		return $attribute_value_content;
2559
	}
2560
2561
	/**
2562
	 * Define a function allowing to manage default value for datetime attributes
2563
	 *
2564
	 * @param mixed $value
2565
	 * @return string The complete interface allowing to manage datetime attribute field
2566
	 */
2567
	function attribute_type_date_config( $value ) {
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...
2568
		$date_config_output = '';
2569
2570
		$input_def['name'] = 'default_value';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$input_def was never initialized. Although not strictly required by PHP, it is generally a good practice to add $input_def = 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...
2571
		$input_def['type'] = 'checkbox';
2572
		$input_def['possible_value'] = 'date_of_current_day';
2573
		$input_def['value'] = !empty($value['default_value']) ? $value['default_value'] : '';
2574
		$input_def['options_label']['custom'] = ' ' . __('Use the date of the day as default value', 'wpshop') . ' <a href="#" title="'.__('Check this box for using date of the day as value when editing a product', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
2575
		$date_config_output .= wpshop_form::check_input_type($input_def, WPSHOP_DBT_ATTRIBUTE);
2576
2577
		$input_def = array();
2578
		$input_def['name'] = '';
2579
		$input_def['id'] = 'wpshop_attributes_edition_table_field_attribute_type_date_options_day_to_show';
2580
		$input_def['type'] = 'checkbox';
2581
		$input_def['valueToPut'] = 'index';
2582
		$input_def['value'] = !empty($value['field_options']['attribute_type_date_options_day_to_show']) ? $value['field_options']['attribute_type_date_options_day_to_show'] : '';
2583
		$input_def['possible_value'] = array('1' => ' ' . __('Monday', 'wpshop'), '2' => ' ' .__('Tuesday', 'wpshop'), '3' => ' ' .__('Wednesday', 'wpshop'), '4' => ' ' .__('Thursday', 'wpshop'), '5' => ' ' .__('Friday', 'wpshop'), '6' => ' ' .__('Saturday', 'wpshop'), '0' => ' ' .__('Sunday', 'wpshop'));
2584
		$input_def['options_label']['original'] = true;
2585
		$date_config_output .= '<div>' . __('Choose available days in date picker', 'wpshop') . '<a href="#" title="'.__('This option allows you to define the available day in final datepicker', 'wpshop').'" class="wpshop_infobulle_marker">?</a>' . '<br/>' . wpshop_form::check_input_type($input_def, WPSHOP_DBT_ATTRIBUTE . '_options[attribute_type_date_options_day_to_show]') . '</div>';
2586
2587
		/**	Past and futur date restriction	*/
2588
		$input_def = array();
2589
		$input_def['name'] = '';
2590
		$input_def['type'] = 'text';
2591
		$date_config_output .= '<div id="wpshop_avalaible_date_for_past_and_futur" >' . __('Calendar past and futur date available', 'wpshop') . '<a href="#" title="'.__('Define if the end user is allowed to choose past and/or futur date', 'wpshop').'" class="wpshop_infobulle_marker">?</a><br/>';
2592
		$available_type_input_def = array();
2593
		$available_type_input_def['name'] = '';
2594
		$available_type_input_def['id'] = 'wpshop_attributes_edition_table_field_attribute_type_date_options_available_date_past_futur_minimum';
2595
		$available_type_input_def['type'] = 'text';
2596
		$available_type_input_def['value'] = !empty($value['field_options']['attribute_type_date_options_available_date_past_futur']['minDate'][0]) ? $value['field_options']['attribute_type_date_options_available_date_past_futur']['minDate'][0] : '';
2597
		$date_config_output .= __('Minimum date to show', 'wpshop') . '<a href="#" title="'.__('If you want the calendar to start today put only 0, if you want to show anterior date, put the number of Day or Month or Year (ex: -1D)', 'wpshop').'" class="wpshop_infobulle_marker">?</a>' . wpshop_form::check_input_type($available_type_input_def, WPSHOP_DBT_ATTRIBUTE . '_options[attribute_type_date_options_available_date_past_futur][minDate]') . '<br/>';
2598
		$available_type_input_def = array();
2599
		$available_type_input_def['name'] = '';
2600
		$available_type_input_def['id'] = 'wpshop_attributes_edition_table_field_attribute_type_date_options_available_date_past_futur_maximum';
2601
		$available_type_input_def['type'] = 'text';
2602
		$available_type_input_def['value'] = !empty($value['field_options']['attribute_type_date_options_available_date_past_futur']['maxDate'][0]) ? $value['field_options']['attribute_type_date_options_available_date_past_futur']['maxDate'][0] : '';
2603
		$date_config_output .= __('Maximum date to show', 'wpshop') . '<a href="#" title="'.__('If you want the calendar to end today put only 0, if you want to show date in futur, put the number of Day or Month or Year (ex: +1M)', 'wpshop').'" class="wpshop_infobulle_marker">?</a>' . wpshop_form::check_input_type($available_type_input_def, WPSHOP_DBT_ATTRIBUTE . '_options[attribute_type_date_options_available_date_past_futur][maxDate]') . '<br/>';
2604
		$date_config_output .= '</div>';
2605
2606
		$input_def = array();
2607
		$input_def['name'] = '';
2608
		$input_def['type'] = 'text';
2609
		$date_config_output .= '
2610
<div id="wpshop_attribute_date_empy_field" class="wpshopHide" ><br/>' . wpshop_form::check_input_type(array_merge($input_def, array('value' => '', 'id' => 'wpshop_attributes_edition_table_field_attribute_type_date_options_available_date_new_input')), WPSHOP_DBT_ATTRIBUTE . '_options[attribute_type_date_options_available_date]') .'</div>
2611
<div id="wpshop_avalaible_date_list_container" >' . __('Choose available date in date picker', 'wpshop') . '<a href="#" title="'.__('This option allows you to define the available date in final datepicker', 'wpshop').'" class="wpshop_infobulle_marker">?</a><br/>';
2612
2613
		$available_type_input_def = array();
2614
		$available_type_input_def['name'] = '';
2615
		$available_type_input_def['id'] = 'wpshop_attributes_edition_table_field_attribute_type_date_options_available_date_type';
2616
		$available_type_input_def['type'] = 'radio';
2617
		$available_type_input_def['valueToPut'] = 'index';
2618
		$available_type_input_def['value'] = !empty($value['field_options']['attribute_type_date_options_available_date_type']) ? $value['field_options']['attribute_type_date_options_available_date_type'] : array('');
2619
		$available_type_input_def['possible_value'] = array('' => __('No restriction', 'wpshop'), 'available' => __('Date below are available', 'wpshop'), 'unavailable' => __('Date below are unvailable', 'wpshop'));
2620
		$available_type_input_def['options_label']['original'] = true;
2621
		$date_config_output .= wpshop_form::check_input_type($available_type_input_def, WPSHOP_DBT_ATTRIBUTE . '_options[attribute_type_date_options_available_date_type]') . '<br/>';
2622
2623
		$existing = 0;
2624
		if ( !empty($value['field_options']['attribute_type_date_options_available_date']) ) {
2625
			foreach ( $value['field_options']['attribute_type_date_options_available_date'] as $index => $value ) {
2626
				if ( !empty($value) ) {
2627
					$input_def['value'] = $value;
2628
					$input_def['id'] = 'wpshop_attributes_edition_table_field_attribute_type_date_options_available_date_' . $index;
2629
					$date_config_output .= wpshop_form::check_input_type($input_def, WPSHOP_DBT_ATTRIBUTE . '_options[attribute_type_date_options_available_date]') . '<br/>';
2630
					$existing++;
2631
				}
2632
			}
2633
		}
2634
		$input_def['value'] = '';
2635
		$input_def['id'] = 'wpshop_attributes_edition_table_field_attribute_type_date_options_available_date';
2636
		$date_config_output .= wpshop_form::check_input_type($input_def, WPSHOP_DBT_ATTRIBUTE . '_options[attribute_type_date_options_available_date]');
2637
		$date_config_output .= '
2638
	<img class="wpshop_icons wpshop_icons_add_new_value_to_available_date_list" title="' . __('Add a new date', 'wpshop') . '" alt="' . __('Add a new date', 'wpshop') . '" src="' . WPSHOP_MEDIAS_ICON_URL . 'add.png" >
2639
</div>';
2640
2641
		return $date_config_output;
2642
	}
2643
2644
	/**
2645
	 * Met a jour un ou plusieurs attributes concernant un produit
2646
	 * @param integer $entityId Id du produit
2647
	 * @param array $values Valeurs d'attributs
2648
	 * @return array
2649
	 */
2650
	public static function setAttributesValuesForItem($entityId, $values=array(), $defaultValueForOthers=false, $from = 'webservice') {
2651
		$message='';
2652
		$attribute_available = array();
2653
		$attribute_final = array();
2654
		$entity_type = get_post_type($entityId);
2655
		$data = self::get_attribute_list_for_item( wpshop_entities::get_entity_identifier_from_code($entity_type), $entityId, WPSHOP_CURRENT_LOCALE);
2656
		foreach($data as $d) $attribute_available[$d->attribute_code] = array('attribute_id' => $d->attribute_id, 'data_type' => $d->data_type);
2657
2658
		// Creation d'un array "propre" et valide pour la fonction self::saveAttributeForEntity
2659
		foreach ( $values as $key => $value ) {
2660
			if ( in_array( $key, array_keys( $attribute_available ) ) ) {
2661
				$attribute_final[$attribute_available[$key]['data_type']][$key] = $value;
2662
			}
2663
			else $message .= sprintf(__('Impossible to set "%s" attribute', 'wpshop'), $key)."\n";
2664
		}
2665
2666
		// Pour les autres attributs non donné on leur affecte leur valeur par défaut
2667
		if ($defaultValueForOthers) {
2668
			$codes = array_keys($values);
2669
			foreach ($data as $d) {
2670
				if (!in_array($d->attribute_code, $codes)) {
2671
					$attribute_final[$d->data_type][$d->attribute_code] = $d->default_value;
2672
				}
2673
			}
2674
		}
2675
2676
		/*	Save the attributes values into wordpress post metadata database in order to have a backup and to make frontend search working	*/
2677
		$productMetaDatas = array();
2678
		foreach ($attribute_final as $attributeType => $attributeValues) {
2679
			foreach ($attributeValues as $attributeCode => $attributeValue) {
2680
				$productMetaDatas[$attributeCode] = $attributeValue;
2681
			}
2682
		}
2683
2684
		switch ( $entity_type ) {
2685
			case WPSHOP_NEWTYPE_IDENTIFIER_PRODUCT:
2686
					$meta_key = WPSHOP_PRODUCT_ATTRIBUTE_META_KEY;
2687
				break;
2688
			default:
2689
					$meta_key = '_' . $entity_type . '_metadata';
2690
				break;
2691
		}
2692
2693
		$current = get_post_meta($entityId, $meta_key, true);
2694
		$current = empty($current) ? array() : $current;
2695
		$productMetaDatas = array_merge($current, $productMetaDatas);
2696
		update_post_meta($entityId, $meta_key, $productMetaDatas);
2697
2698
		if (!empty($attribute_final)) {
2699
			self::saveAttributeForEntity($attribute_final, wpshop_entities::get_entity_identifier_from_code($entity_type), $entityId, WPSHOP_CURRENT_LOCALE, $from);
2700
		}
2701
2702
		return array('status' => empty($message), 'message' => $message);
2703
	}
2704
2705
	/**
2706
	 * Recupere les informations concernant une option donnees dans la liste d'un attribut de type liste deroulante
2707
	 *
2708
	 * @param integer $option_id L'identifiant de l'option dont on veut recuperer les informations
2709
	 * @param string $field optionnal Le champs correspondant a l'information que l'on souhaite recuperer
2710
	 * @return string $info L'information que l'on souhaite
2711
	 */
2712
	public static function get_attribute_type_select_option_info($option_id, $field = 'label', $attribute_data_type = 'custom', $only_value = false) {
2713
		global $wpdb;
2714
		if( ! is_numeric( $option_id ) ) {
2715
			return '';
2716
		}
2717
		$option_id = (int) $option_id;
2718
		switch ( $attribute_data_type ) {
2719
			case 'internal':
2720
				$entity_infos = get_post($option_id);
2721
				if ( !empty($entity_infos) ) {
2722
					if ( !$only_value ) {
2723
						/** Template parameters */
2724
						$template_part = 'product_attribute_value_internal';
2725
						$tpl_component = array();
2726
						$tpl_component['ATTRIBUTE_VALUE_POST_LINK'] = get_permalink($option_id);
2727
						$tpl_component['ATTRIBUTE_VALUE_POST_TITLE'] = $entity_infos->post_title;
2728
2729
						foreach ( $entity_infos as $post_definition_key => $post_definition_value ) {
2730
							$tpl_component['ATTRIBUTE_VALUE_' . strtoupper($post_definition_key)] = $entity_infos->$post_definition_key;
2731
						}
2732
2733
						/** Build template	*/
2734
						$info = wpshop_display::display_template_element($template_part, $tpl_component);
2735
						unset($tpl_component);
2736
					}
2737
					else {
2738
						$info = $entity_infos->post_title;
2739
					}
2740
				}
2741
				break;
2742
2743
			default:
2744
				if ( ! array_key_exists( $option_id, self::$select_option_info_cache ) ) {
2745
					$query = $wpdb->prepare("SELECT " . $field . " FROM ".WPSHOP_DBT_ATTRIBUTE_VALUES_OPTIONS." WHERE id=%d LIMIT 1", $option_id);
2746
					self::$select_option_info_cache[$option_id] = $wpdb->get_var($query);
2747
				}
2748
				$info = self::$select_option_info_cache[$option_id];
2749
			break;
2750
		}
2751
2752
		return $info;
0 ignored issues
show
Bug introduced by
The variable $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...
2753
	}
2754
2755
	/**
2756
	 * Get the list of existing element for list type attribute
2757
	 *
2758
	 * @param integer $attribute_id
2759
	 * @return object A wordpress database object with the list of existing element
2760
	 */
2761
	function get_select_option_list_($attribute_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...
2762
		global $wpdb;
2763
		$query = $wpdb->prepare("
2764
			SELECT ATTRIBUTE_COMBO_OPTION.id, ATTRIBUTE_COMBO_OPTION.label as name, ATTRIBUTE_COMBO_OPTION.value , ATTRIBUTE_VALUE_INTEGER.value_id
2765
			, ATT.default_value, ATT.data_type_to_use, ATT.use_ajax_for_filling_field
2766
			FROM " . WPSHOP_DBT_ATTRIBUTE . " AS ATT
2767
				LEFT JOIN " . WPSHOP_DBT_ATTRIBUTE_VALUES_OPTIONS . " AS ATTRIBUTE_COMBO_OPTION ON ((ATTRIBUTE_COMBO_OPTION.attribute_id = ATT.id) AND (ATTRIBUTE_COMBO_OPTION.status = 'valid'))
2768
				LEFT JOIN " . WPSHOP_DBT_ATTRIBUTE_VALUES_INTEGER . " AS ATTRIBUTE_VALUE_INTEGER ON ((ATTRIBUTE_VALUE_INTEGER.attribute_id = ATTRIBUTE_COMBO_OPTION.attribute_id) AND (ATTRIBUTE_VALUE_INTEGER.value = ATTRIBUTE_COMBO_OPTION.id))
2769
			WHERE ATT.id = %d
2770
				AND ATT.status = 'valid'
2771
			GROUP BY ATTRIBUTE_COMBO_OPTION.value
2772
			ORDER BY ATTRIBUTE_COMBO_OPTION.position", $attribute_id);
2773
		$list = $wpdb->get_results($query);
2774
2775
		return $list;
2776
	}
2777
2778
	/**
2779
	 * Recupere la liste des options pour les attributs de type liste deroulante suivant le type de donnees choisi (personnalise ou interne a wordpress)
2780
	 *
2781
	 * @param integer $attribute_id L'identifiant de l'attribut pour lequel on souhaite recuperer la liste des options
2782
	 * @param string $data_type optionnal Le type de donnees choisi pour cet attribut (custom | internal)
2783
	 * @return string Le resultat sous forme de code html pour la liste des options
2784
	 */
2785
	function get_select_options_list($attribute_id, $data_type='custom') {
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...
2786
		global $wpdb;
2787
		$output = '';
2788
2789
		$attribute_select_options = self::get_select_option_list_($attribute_id);
2790
2791
		/*	Add possibily to choose datat type to use with list	*/
2792
		if(empty($attribute_id) || (!empty($attribute_select_options) && empty($attribute_select_options[0]->data_type_to_use))){
2793
			unset($input_def);$input_def=array();
2794
			$input_def['label'] = __('Type of data for list', 'wpshop');
2795
			$input_def['type'] = 'radio';
2796
			$input_def['name'] = 'data_type_to_use';
2797
			$input_def['valueToPut'] = 'index';
2798
			$input_def['possible_value'] = unserialize(WPSHOP_ATTR_SELECT_TYPE);
2799
			$input_def['option'] = 'class="wpshop_cls wpshop_attr_combo_data_type"';
2800
			$input_def['value'] = $data_type.'_data';
2801
			$input_def['options_label']['original'] = true;
2802
			$output = wpshop_form::check_input_type($input_def, WPSHOP_DBT_ATTRIBUTE);
2803
		}
2804
2805
		if(!empty($attribute_id) || !empty($data_type)){
2806
			$defaut_value = ( !empty($attribute_select_options[0]) && !empty($attribute_select_options[0]->default_value) ) ? $attribute_select_options[0]->default_value : null;
2807
			$default_is_serial = false;
2808
			if ( !empty($attribute_select_options[0]->default_value) && ($attribute_select_options[0]->default_value == serialize(false) || wpshop_tools::is_serialized( $attribute_select_options[0]->default_value ) ) ) {
2809
				$defaut_value = unserialize($attribute_select_options[0]->default_value);
2810
				$default_is_serial = true;
2811
			}
2812
			/**	Add a custom text first item of list	*/
2813
			$output .= '<div class="wpshop_cls" ><label for="text_for_empty_value" >' . __('Text displayed when no value selected', 'wpshop') . '</label> <input type="text" name="' . WPSHOP_DBT_ATTRIBUTE . '[default_value][field_options][label_for_first_item]" value="' . (($default_is_serial && is_array($defaut_value) && !empty($defaut_value["field_options"]["label_for_first_item"])) ? stripslashes( $defaut_value["field_options"]["label_for_first_item"] ) : __('Choose a value', 'wpshop')) . '" id="text_for_empty_value" /></div>';
2814
2815
			if((($data_type == 'custom') && empty($attribute_select_options)) || (!empty($attribute_select_options) && !empty($attribute_select_options[0]->data_type_to_use) && ($attribute_select_options[0]->data_type_to_use == 'custom'))){
2816
				$sub_output = '';
2817
				if ( !empty($attribute_select_options) && !empty($attribute_select_options[0]) && !empty($attribute_select_options[0]->id) ) {
2818
					$sub_output .= '
2819
					<li class="wpshop_attribute_combo_options_container ui-state-disabled" >
2820
						<input type="radio" name="' . WPSHOP_DBT_ATTRIBUTE . '[default_value][default_value]" value="" id="default_value_empty" ' . (($default_is_serial && is_array($defaut_value) && empty($defaut_value["default_value"])) || empty($defaut_value) ? 'checked ' : '') . '/> <label for="default_value_empty">' . __('No default value', 'wpshop') . '</label>
2821
					</li>';
2822
					foreach ($attribute_select_options as $options) {
2823
						$tpl_component = array();
2824
						$tpl_component['ADMIN_ATTRIBUTE_VALUES_OPTION_ID'] = $options->id;
2825
						$tpl_component['ADMIN_ATTRIBUTE_VALUES_OPTION_NAME'] = $options->name;
2826
						$tpl_component['ADMIN_ATTRIBUTE_VALUES_OPTION_DEFAULT_VALUE'] = $options->default_value;
2827
						$tpl_component['ADMIN_ATTRIBUTE_VALUES_OPTION_VALUE'] = str_replace(".", ",", $options->value);
2828
						$tpl_component['ADMIN_ATTRIBUTE_VALUES_OPTION_STATE'] = (!empty($options->id) && (($default_is_serial && is_array($defaut_value) && !empty($defaut_value["default_value"]) && ($defaut_value["default_value"] == $options->id))) ? ' checked="checked"' : '');
2829
						$tpl_component['ADMIN_ATTRIBUTE_VALUE_OPTIN_ACTIONS'] = '';
2830 View Code Duplication
						if( current_user_can('wpshop_delete_attributes_select_values') && ($options->value_id >= 0) ):
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...
2831
							$tpl_component['ADMIN_ATTRIBUTE_VALUE_OPTIN_ACTIONS'] .= wpshop_display::display_template_element('wpshop_admin_attr_option_value_item_deletion', $tpl_component, array('type' => WPSHOP_DBT_ATTRIBUTE, 'id' => $attribute_id), 'admin');
2832
						endif;
2833
						$sub_output .= wpshop_display::display_template_element('wpshop_admin_attr_option_value_item', $tpl_component, array('type' => WPSHOP_DBT_ATTRIBUTE, 'id' => $attribute_id), 'admin');
2834
						unset($tpl_component);
2835
					}
2836
				}
2837
				$add_button = $add_dialog_box = $user_more_script = '';
2838 View Code Duplication
				if( current_user_can('wpshop_add_attributes_select_values') ) {
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...
2839
2840
					$dialog_title = __('New value for attribute', 'wpshop');
2841
					$dialog_identifier = 'wpshop_new_attribute_option_value_add';
2842
					$dialog_input_identifier = 'wpshop_new_attribute_option_value';
2843
					ob_start();
2844
					include(WPSHOP_TEMPLATES_DIR.'admin/add_new_element_dialog.tpl.php');
2845
					$add_dialog_box = ob_get_contents();
2846
					ob_end_clean();
2847
2848
					$add_button_text = __('Add a value for this attribute', 'wpshop');
2849
					$add_button_parent_class = 'wpshop_attribute_option_value_add';
2850
					$add_button_name = 'wpshop_add_option_to_select';
2851
					ob_start();
2852
					include(WPSHOP_TEMPLATES_DIR.'admin/add_new_element_with_dialog.tpl.php');
2853
					$add_button = ob_get_contents();
2854
					ob_end_clean();
2855
2856
					$user_more_script = '
2857
			jQuery("#'.$dialog_identifier.'").dialog({
2858
				modal: true,
2859
				dialogClass: "wpshop_uidialog_box",
2860
				autoOpen:false,
2861
				show: "blind",
2862
				resizable: false,
2863
				buttons:{
2864
					"'.__('Add', 'wpshop').'": function(){
2865
						var data = {
2866
							action: "new_option_for_select",
2867
							wpshop_ajax_nonce: "' . wp_create_nonce("wpshop_new_option_for_attribute_creation") . '",
2868
							attribute_new_label: jQuery("#'.$dialog_input_identifier.'").val(),
2869
							attribute_identifier: "' . $attribute_id . '"
2870
						};
2871
						jQuery.post(ajaxurl, data, function(response) {
2872
							if( response[0] ) {
2873
								jQuery("#sortable_attribute li:last-child").before(response[1]);
2874
								jQuery("#wpshop_new_attribute_option_value_add").dialog("close");
2875
							}
2876
							else {
2877
								alert(response[1]);
2878
							}
2879
							jQuery("#wpshop_new_attribute_option_value_add").children("img").hide();
2880
						}, "json");
2881
2882
						jQuery(this).children("img").show();
2883
					},
2884
					"'.__('Cancel', 'wpshop').'": function(){
2885
						jQuery(this).dialog("close");
2886
					}
2887
				},
2888
				close:function(){
2889
					jQuery("#'.$dialog_input_identifier.'").val("");
2890
				}
2891
			});
2892
			jQuery(".'.$add_button_parent_class.' input").click(function(){
2893
				jQuery("#'.$dialog_identifier.'").dialog("open");
2894
			});';
2895
2896
				}
2897
				$output .= $add_dialog_box . '
2898
	<ul id="sortable_attribute" class="wpshop_cls" >'.(count($attribute_select_options)>5 ? $add_button : '').$sub_output.$add_button.'
2899
	</ul>
2900
	<input type="hidden" value="' . wp_create_nonce("wpshop_new_option_for_attribute_deletion") . '" name="wpshop_new_option_for_attribute_deletion_nonce" id="wpshop_new_option_for_attribute_deletion_nonce" />
2901
	<script type="text/javascript" >
2902
		wpshop(document).ready(function() {
2903
			jQuery("#sortable_attribute").sortable({
2904
				revert: true,
2905
				items: "li:not(.ui-state-disabled)"
2906
			});
2907
			' . $user_more_script . '
2908
			jQuery(".wpshop_attr_combo_data_type").live("click", function(){
2909
				if(jQuery(this).is(":checked")){
2910
					jQuery(".wpshop_attributes_edition_table_field_input_default_value").html(jQuery("#wpshopLoadingPicture").html());
2911
					var data = {
2912
						action: "attribute_output_type",
2913
						current_type: jQuery("#wpshop_attributes_edition_table_field_id_frontend_input").val(),
2914
						elementIdentifier: "'.$attribute_id.'",
2915
						data_type_to_use: jQuery(this).val(),
2916
						wpshop_ajax_nonce: "' . wp_create_nonce("wpshop_attribute_output_type_selection") . '"
2917
					};
2918
					jQuery.post(ajaxurl, data, function(response) {
2919
						jQuery(".wpshop_attributes_edition_table_field_input_default_value").html(response[0]);
2920
						jQuery(".wpshop_attributes_edition_table_field_label_default_value label").html(response[1]);
2921
						jQuery("#wpshop_attributes_edition_table_field_id_frontend_input").html();
2922
					}, "json");
2923
				}
2924
			});
2925
2926
		});
2927
	</script>';
2928
			}
2929
			elseif((($data_type == 'internal') && empty($attribute_select_options)) || (!empty($attribute_select_options) && !empty($attribute_select_options[0]->data_type_to_use) && ($attribute_select_options[0]->data_type_to_use == 'internal'))){
2930
				$sub_output='';
0 ignored issues
show
Unused Code introduced by
$sub_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...
2931
				$wp_types = unserialize(WPSHOP_INTERNAL_TYPES);
2932
				unset($input_def);$input_def=array();
2933
				$input_def['label'] = __('Type of data for list', 'wpshop');
2934
				$input_def['type'] = 'select';
2935
				$input_def['name'] = 'default_value][default_value';
2936
				$input_def['id'] = 'default_value';
2937
				$input_def['valueToPut'] = 'index';
2938
				$input_def['possible_value'] = $wp_types;
2939
				$input_def['value'] = (($default_is_serial && is_array($defaut_value) && !empty($defaut_value["default_value"])) ? $defaut_value["default_value"] : (!empty($defaut_value) ? $defaut_value : null));
2940
				$combo_wp_type = wpshop_form::check_input_type($input_def, WPSHOP_DBT_ATTRIBUTE);
2941
				$output .= '<div class="wpshop_cls">'.$combo_wp_type.'</div>';
2942
				if ( !empty($attribute_id) ) {
2943
					$option_list = '<div>' . __('You can reorder element for display them in the order you want into frontend part', 'wpshop') . '</div>';
2944
					$options_for_current_attribute = query_posts( array('post_type' => $input_def['value'], 'posts_per_page' => -1, 'orderby' => 'menu_order', 'order' => 'ASC' ) );
2945
					if ( !empty($options_for_current_attribute) ) {
2946
						$option_list .= '<ul class="wpshop_attribute_combo_values_list_container" >';
2947
						$current_order = ' ';
2948
						foreach ( $options_for_current_attribute as $options_def ) {
2949
							$current_order .= 'post_' . $options_def->ID . ',';
2950
							$option_list .= '<li id="post_' . $options_def->ID . '" class="wpshop_attribute_combo_values_list_item wpshop_attribute_combo_values_list_item_' . $options_def->ID . '" ><span class="wpshop_internal_value_for_option_list_identifier" >#' . $options_def->ID . '</span> ' . $options_def->post_title . '</li>';
2951
						}
2952
						$option_list .= '</ul><input type="hidden" value="' . substr($current_order, 0, -1) . '" name="' . WPSHOP_DBT_ATTRIBUTE . '[wpshop_attribute_combo_values_list_order_def]" id="wpshop_attribute_combo_values_list_order_def" />';
2953
					}
2954
					$output .= '<div class="wpshop_cls">'.$option_list.'</div>';
2955
				}
2956
			}
2957
		}
2958
2959
		return $output;
2960
	}
2961
2962
	/**
2963
	 * Get the attribute list affected to an entity in order to generate a shortcode
2964
	 *
2965
	 * @param integer $entity_id The entity identifier for retrieving attribute list
2966
	 * @param string $list_for The type of shortcode we want to generate
2967
	 * @param string $current_post_type The post type of current edited element
2968
	 *
2969
	 * @return string The html output
2970
	 */
2971
	public static function get_attribute_list($entity_id = 0, $list_for = 'product_by_attribute', $current_post_type = '') {
0 ignored issues
show
Unused Code introduced by
The parameter $current_post_type 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...
2972
		global $wpdb;
2973
		$output = '';
2974
2975
		/*	If no entity is specified, take product as default entity	*/
2976
		$entity_id = empty($entity_id) ? wpshop_entities::get_entity_identifier_from_code(WPSHOP_NEWTYPE_IDENTIFIER_PRODUCT) : $entity_id;
2977
2978
		/*	Get attribute list for the selected enttiy	*/
2979
		$attribute_list_for_entity = self::getElement($entity_id, "'valid'", 'entity_id', true);
2980
2981
		/*	Read the list	*/
2982
		if ( !empty ($attribute_list_for_entity ) ) {
2983
			foreach ( $attribute_list_for_entity as $attribute) {
2984
				switch ($list_for) {
2985
					case 'attribute_value':
2986
							$checkbox_state = ' ';
2987
							$attribute_possible_values = '
2988
							<div class="wpshop_shortcode_element_attribute_value_product_list wpshop_shortcode_element_attribute_value_product_list_' . $attribute->id . '_container hidden" >
2989
								<select id="wpshop_shortcode_element_attribute_value_product_list_' . $attribute->id . '" class="wpshop_shortcode_element_attribute_value_product_list" >';
2990
2991
							global $post;
2992
							$posts = get_posts( array('post_type' => WPSHOP_NEWTYPE_IDENTIFIER_PRODUCT, 'numberposts' => -1) );
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $posts is correct as get_posts(array('post_ty..., 'numberposts' => -1)) (which targets get_posts()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
2993
							foreach( $posts as $post ) :
0 ignored issues
show
Bug introduced by
The expression $posts of type null is not traversable.
Loading history...
2994
								setup_postdata($post);
2995
								$attribute_possible_values .= '<option value="' . get_the_ID() . '" >' . get_the_ID() . ' - ' . get_the_title() . '</option>';
2996
							endforeach;
2997
2998
							$attribute_possible_values .= '
2999
								</select>
3000
							</div>';
3001
						break;
3002
3003
					default:
3004
						$query = $wpdb->prepare("SELECT * FROM " . WPSHOP_DBT_ATTRIBUTE_VALUES_PREFIX . $attribute->data_type . " WHERE entity_type_id=%d AND attribute_id=%d GROUP BY value", $entity_id, $attribute->id);
3005
						$attribute_values = $wpdb->get_results($query);
3006
3007
						$checkbox_state = 'disabled ';
3008
						$attribute_possible_values = '';
3009
						if ( !empty($attribute_values) ) {
3010
							$checkbox_state = '';
3011
							$attribute_possible_values = '
3012
							<div class="wpshop_shortcode_element_product_listing_per_attribute_value wpshop_shortcode_element_prodcut_listing_per_attribute_value_' . $attribute->code . '_container" >
3013
								<select id="wpshop_attribute_value_for_shortcode_generation_' . $attribute->id . '" class="wpshop_shortcode_element_prodcut_listing_per_attribute_value hidden" >';
3014
3015
								if ( ($attribute->data_type == 'integer') && ( ($attribute->backend_input == 'select') || ($attribute->backend_input == 'multiple-select') ) ) {
3016
									$query = $wpdb->prepare("SELECT * FROM " . WPSHOP_DBT_ATTRIBUTE_VALUES_OPTIONS . " WHERE attribute_id=%d ORDER BY position", $attribute->id);
3017
									$possible_values = $wpdb->get_results($query);
3018
									$already_selected_values = array();
3019
									foreach ($attribute_values as $attribute_value) {
3020
										if ( !empty($attribute_value->value) ) {
3021
											$already_selected_values[] = $attribute_value->value;
3022
										}
3023
									}
3024
									foreach ($possible_values as $value) {
3025
										if ( in_array( $value->id, $already_selected_values ) ) {
3026
											$attribute_possible_values .= '
3027
									<option value="' . $value->value . '" >' . $value->label . '</option>';
3028
										}
3029
									}
3030
								}
3031
								else {
3032
									foreach ($attribute_values as $attribute_value) {
3033
										if ( !empty($attribute_value->value) ) {
3034
											$attribute_possible_values .= '
3035
									<option value="' . $attribute_value->value . '" >' . $attribute_value->value . '</option>';
3036
										}
3037
									}
3038
								}
3039
								$attribute_possible_values .= '
3040
								</select>
3041
							</div>';
3042
						}
3043
						break;
3044
				}
3045
				$output .= '
3046
				<li class="wpshop_shortcode_element_container wpshop_shortcode_element_container_attributes" >
3047
					<input type="checkbox" name="' . $attribute->code . '" class="wpshop_shortcode_element wpshop_shortcode_element_attribute wpshop_shortcode_element_attribute_' . $attribute->id . '" value="' . (($list_for == 'product_by_attribute') ? $attribute->code : $attribute->id) . '" id="wpshop_attribute_' . $attribute->id . '" ' . $checkbox_state . '> <label for="wpshop_attribute_' . $attribute->id . '" >' . __($attribute->frontend_label, 'wpshop') . '</label>' . $attribute_possible_values . '
3048
				</li>';
3049
			}
3050
		}
3051
3052
		return $output;
3053
	}
3054
3055
	/**
3056
	 * Retrieve the attribute list into an attribute set section from a given attribute code
3057
	 *
3058
	 * @param string $attribute_code The attribute code that allows to define the attribute set section to get attribute list for
3059
	 *
3060
	 * @return object The attribute list as a wordpress database object
3061
	 */
3062
	function get_attribute_list_in_same_set_section( $attribute_code ) {
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...
3063
		global $wpdb;
3064
3065
		$attribute_def = wpshop_attributes::getElement($attribute_code, "'valid'", 'code');
3066
3067
		/** Get the entire list of attribute in price set section for display	*/
3068
		$query = $wpdb->prepare( "SELECT entity_type_id, attribute_set_id, attribute_group_id FROM " . WPSHOP_DBT_ATTRIBUTE_DETAILS . " WHERE attribute_id = %d AND status = 'valid'", $attribute_def->id);
3069
		$attribute_attribution_def = $wpdb->get_row($query);
3070
3071
		$query = $wpdb->prepare( "
3072
							SELECT ATTR.code, is_visible_in_front_listing, is_visible_in_front
3073
							FROM " . WPSHOP_DBT_ATTRIBUTE_DETAILS . " AS SET_SECTION_DETAIL
3074
								INNER JOIN " . WPSHOP_DBT_ATTRIBUTE . " AS ATTR ON (ATTR.id = SET_SECTION_DETAIL.attribute_id)
3075
							WHERE entity_type_id = %d
3076
								AND attribute_set_id = %d
3077
								AND attribute_group_id = %d",
3078
				$attribute_attribution_def->entity_type_id, $attribute_attribution_def->attribute_set_id, $attribute_attribution_def->attribute_group_id );
3079
		$atribute_list = $wpdb->get_results($query);
3080
3081
		return $atribute_list;
3082
	}
3083
3084
	/**
3085
	 * Get all attribute available for current
3086
	 * @param unknown_type $current_entity_id
3087
	 * @return Ambigous <multitype:, multitype:NULL >
3088
	 */
3089
	public static function get_variation_available_attribute( $current_entity_id ) {
3090
		global $wpdb;
3091
		$final_list = array();
3092
3093
		/**	Get all attributes defined as usable into product variation for the product type and group	*/
3094
		$query = $wpdb->prepare(
3095
				"SELECT ATT.*, ENTITY_META.meta_value
3096
				FROM " . self::getDbTable() . " AS ATT
3097
					INNER JOIN " . WPSHOP_DBT_ATTRIBUTE_DETAILS. " AS ATT_DETAILS ON ((ATT_DETAILS.attribute_id = ATT.id) AND (ATT_DETAILS.entity_type_id = %d) AND (ATT_DETAILS.status = 'valid'))
3098
					INNER JOIN " . $wpdb->postmeta . " AS ENTITY_META ON ((ENTITY_META.meta_key = %s) AND (ENTITY_META.meta_value = ATT_DETAILS.attribute_set_id))
3099
				WHERE ATT.status IN ('valid')
3100
					AND ATT.is_used_for_variation = %s
3101
					AND ENTITY_META.post_id = %d
3102
				GROUP BY ATT_DETAILS.position, ENTITY_META.post_id, ATT.code
3103
				ORDER BY ATT_DETAILS.position", wpshop_entities::get_entity_identifier_from_code(get_post_type($current_entity_id)), WPSHOP_PRODUCT_ATTRIBUTE_SET_ID_META_KEY, 'yes', $current_entity_id
3104
		);
3105
		$attribute_list = $wpdb->get_results($query);
3106
		foreach ($attribute_list as $attribute) {
3107
			if ( !in_array($attribute->code, unserialize(WPSHOP_VARIATION_ATTRIBUTE_TO_HIDE)) && in_array($attribute->backend_input, array('select', 'multiple-select')) ) {
3108
				$attribute_values_for_variations = wpshop_attributes::get_affected_value_for_list( $attribute->code, $current_entity_id, $attribute->data_type_to_use );
3109
3110
				if ( empty($attribute_values_for_variations) ) {
3111
					$final_list['unavailable'][$attribute->code]['label'] = $attribute->frontend_label;
3112
					$final_list['unavailable'][$attribute->code]['values'] = array();
3113
					$final_list['unavailable'][$attribute->code]['attribute_complete_def'] = $attribute;
3114
				}
3115
				else {
3116
					$final_list['available'][$attribute->code]['label'] = $attribute->frontend_label;
3117
					$final_list['available'][$attribute->code]['values'] = $attribute_values_for_variations;
3118
					$final_list['available'][$attribute->code]['attribute_complete_def'] = $attribute;
3119
				}
3120
			}
3121
		}
3122
		return $final_list;
3123
	}
3124
3125
	/**
3126
	 *
3127
	 * @param integer $current_entity_id The current element edited
3128
	 * @return Ambigous <string, string, mixed>
3129
	 */
3130
	public static function get_variation_available_attribute_display( $current_entity_id, $variation_type = 'multiple' ) {
3131
		$attribute_list = wpshop_attributes::get_variation_available_attribute($current_entity_id);
0 ignored issues
show
Documentation introduced by
$current_entity_id is of type integer, 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...
3132
3133
		$attribute_defined_as_available_for_variation = '';
3134
		if ( !empty($attribute_list) ) {
3135
			foreach ($attribute_list as $list_type => $attribute_list_by_type) {
3136
				$sub_attribute_list = '';
3137
				foreach ($attribute_list_by_type as $attribute_code => $attribute_def) {
3138
					$tpl_component = array();
3139
					if ( $list_type == 'available' ) {
3140
						$tpl_component['ADMIN_VARIATIONS_DEF_ATTRIBUTE_LABEL_STATE'] = '';
3141
						$tpl_component['ADMIN_VARIATIONS_DEF_LIST_ATTRIBUTE_CHECKBOX_STATE'] = '';
3142
						$tpl_component['ADMIN_VARIATIONS_DEF_ATTRIBUTE_TO_USE_LABEL_EXPLAINATION'] = '';
3143
					}
3144
					else {
3145
						$tpl_component['ADMIN_VARIATIONS_DEF_ATTRIBUTE_LABEL_STATE'] = ' class="wpshop_unavailable_label_variation_definition" ';
3146
						$tpl_component['ADMIN_VARIATIONS_DEF_LIST_ATTRIBUTE_CHECKBOX_STATE'] = ' disabled="disabled"';
3147
						$tpl_component['ADMIN_VARIATIONS_DEF_ATTRIBUTE_TO_USE_LABEL_EXPLAINATION'] = '';
3148
					}
3149
3150
					$tpl_component['ADMIN_ATTRIBUTE_CODE_FOR_VARIATION'] = $attribute_code;
3151
					$tpl_component['ADMIN_VARIATIONS_DEF_ATTRIBUTE_TO_USE_NAME'] = $attribute_code;
3152
					$tpl_component['ADMIN_VARIATION_ATTRIBUTE_CONTAINER_CLASS'] = ' wpshop_attribute_for_variation_' . $attribute_code;
3153
					$tpl_component['ADMIN_VARIATION_NEW_SINGLE_LABEL'] = __( $attribute_def['label'], 'wpshop' );
3154
					$tpl_component['ADMIN_VARIATION_NEW_SINGLE_INPUT'] = '';
3155
					if ( $variation_type == 'single' ) {
3156
						$attribute_output_def = wpshop_attributes::get_attribute_field_definition( $attribute_def['attribute_complete_def'], $attribute_def['values'], array('from' => 'frontend', 'field_custom_name_prefix' => 'variation_attr', 'input_class' => ' variation_attribute_usable_input') );
3157
						if ( !empty($attribute_output_def['possible_value']) ) {
3158
							foreach( $attribute_output_def['possible_value'] as $value_id => $value ){
3159
								if ( !in_array($value_id, $attribute_def['values']) ) {
3160
									unset($attribute_output_def['possible_value'][$value_id]);
3161
								}
3162
							}
3163
						}
3164
						$tpl_component['ADMIN_VARIATION_NEW_SINGLE_INPUT'] = wpshop_form::check_input_type($attribute_output_def, $attribute_output_def['input_domain']);
3165
					}
3166
					$sub_attribute_list .= wpshop_display::display_template_element('wpshop_admin_variation_attribute_line', $tpl_component, array(), 'admin');
3167
					unset($tpl_component);
3168
				}
3169
3170
				$attribute_defined_as_available_for_variation .= wpshop_display::display_template_element((($list_type == 'available') ? 'wpshop_admin_attribute_for_variation_list' : 'wpshop_admin_unvailable_attribute_for_variation_list'), array('ADMIN_VARIATIONS_DEF_LIST_CONTAINER_CLASS' => '', 'ADMIN_VARIATIONS_DEF_LIST_CONTAINER' => $sub_attribute_list), array(), 'admin');
3171
			}
3172
		}
3173
3174
		return array($attribute_defined_as_available_for_variation, ( (!empty($attribute_list['available']) ) ? $attribute_list['available'] : ''), ( ( !empty($attribute_list['unavailable']) ) ? $attribute_list['unavailable'] : ''));
3175
	}
3176
3177
	/**
3178
	 * Get attribute defined as product option specific attribute
3179
	 *
3180
	 * @param array $variations_attribute_parameters Allows to give some parameters for customize list
3181
	 * @return string The output for all specific attribute in each product with option
3182
	 */
3183
	public static function get_variation_attribute( $variations_attribute_parameters ) {
3184
		$output = '';
3185
3186
		$attribute_list = wpshop_attributes::getElement('yes', "'valid'", "is_used_in_variation", true);
3187
		if ( !empty( $attribute_list ) ) {
3188
			$tpl_component = array();
3189
			$tpl_component['ADMIN_VARIATION_DETAIL'] = '';
3190
			$price_piloting_option = get_option('wpshop_shop_price_piloting');
0 ignored issues
show
Unused Code introduced by
$price_piloting_option 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...
3191
			foreach ( $attribute_list as $attribute_def ) {
3192
3193
				$variations_attribute_parameters['field_custom_name_prefix'] = $variations_attribute_parameters['field_name'] . '[attribute][' . $attribute_def->data_type . ']';
3194
				$attribute_output_def = wpshop_attributes::get_attribute_field_definition( $attribute_def, (!empty($variations_attribute_parameters['variation_dif_values'][$attribute_def->code]) ? $variations_attribute_parameters['variation_dif_values'][$attribute_def->code] : ''), $variations_attribute_parameters );
3195
3196
				$field_output = $attribute_output_def['output'];
3197
3198
				/*	Build array for output complete customization	*/
3199
				$tpl_component['ADMIN_VARIATION_DETAIL_LABEL_' . strtoupper($attribute_def->code)] = $attribute_output_def['label'];
3200
				$tpl_component['ADMIN_VARIATION_DETAIL_INPUT_' . strtoupper($attribute_def->code)] = $field_output;
3201
				$sub_tpl_component = array();
3202
				$sub_tpl_component['ADMIN_VARIATION_DETAIL_DEF_CODE'] = ' wpshop_variation_special_value_container_' . $attribute_output_def['name'];
3203
				$sub_tpl_component['ADMIN_VARIATION_DETAIL_DEF_ID'] = $attribute_output_def['id'];
3204
				$sub_tpl_component['ADMIN_VARIATION_DETAIL_DEF_LABEL'] = $attribute_output_def['label'];
3205
				$sub_tpl_component['ADMIN_VARIATION_DETAIL_DEF_INPUT'] = $field_output;
3206 View Code Duplication
				if( isset( $variations_attribute_parameters['post_id'] ) ) {
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...
3207
					$attribute_option_display = $attribute_def->backend_input=='select' && (strtolower( __(self::get_attribute_type_select_option_info($attribute_output_def['value'], 'value'), 'wpshop') ) == strtolower( __('yes', 'wpshop') )) ? '' : ' wpshopHide';
3208
					$sub_tpl_component['ADMIN_VARIATION_DETAIL_DEF_INPUT'] .= '<div class="attribute_option_'.$attribute_def->code.''.$attribute_option_display.'">'.self::get_attribute_option_fields($variations_attribute_parameters['post_id'], $attribute_def->code).'</div>';
3209
				}
3210
				$tpl_component['ADMIN_VARIATION_DETAIL'] .= wpshop_display::display_template_element('wpshop_admin_variation_item_details_line', $sub_tpl_component, array(), 'admin');
3211
				unset($sub_tpl_component);
3212
			}
3213
			$output .= wpshop_display::display_template_element('wpshop_admin_variation_item_details', $tpl_component, array(), 'admin');
3214
		}
3215
3216
		return $output;
3217
	}
3218
3219
	public static function get_attribute_user_defined( $use_defined_parameters, $status = "'publish'" ) {
0 ignored issues
show
Unused Code introduced by
The parameter $status 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...
3220
		global $wpdb;
3221
		$attribute_user_defined_list = array();
0 ignored issues
show
Unused Code introduced by
$attribute_user_defined_list 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...
3222
3223
		$query = $wpdb->prepare(
3224
				"SELECT ATT.*, ENTITY.post_name as entity
3225
				FROM " . self::getDbTable() . " AS ATT
3226
					INNER JOIN " . $wpdb->posts . " AS ENTITY ON (ENTITY.ID = ATT.entity_id)
3227
					INNER JOIN " . $wpdb->postmeta . " AS ENTITY_META ON ((ENTITY_META.post_id = ENTITY_ID))
3228
				WHERE ATT.status IN ('valid')
3229
					AND ATT.is_user_defined = %s
3230
					AND ATT.is_used_for_variation = %s
3231
					AND ENTITY.post_name = %s
3232
				GROUP BY ATT.id", 'yes', 'no', $use_defined_parameters['entity_type_id']
3233
		);
3234
		$attribute_user_defined_list = $wpdb->get_results($query);
3235
3236
		return $attribute_user_defined_list;
3237
	}
3238
3239
	/**
3240
	 * Define the different field available for bulk edition for entities. Attributes to display are defined by checking box in attribute option
3241
	 *
3242
	 * @param string $column_name The column name for output type definition
3243
	 * @param string $post_type The current
0 ignored issues
show
Bug introduced by
There is no parameter named $post_type. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

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

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

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

Loading history...
3244
	 *
3245
	 */
3246
	function quick_edit( $column_name, $entity ) {
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...
3247
		switch ( $entity ) {
3248
			case WPSHOP_NEWTYPE_IDENTIFIER_PRODUCT:
3249
				$attribute_def = wpshop_attributes::getElement($column_name, "'valid'", 'code');
3250
				if ( !empty($attribute_def) ) {
3251
					$input_def = self::get_attribute_field_definition( $attribute_def, '', array('input_class' => ' wpshop_bulk_and_quick_edit_input') );
3252
					$input = wpshop_form::check_input_type($input_def, $input_def['input_domain']);
3253
?>
3254
	<div class="wpshop_bulk_and_quick_edit_column_container wpshop_bulk_and_quick_edit_column_<?php echo $column_name; ?>_container">
3255
		<span class="wpshop_bulk_and_quick_edit_column_label wpshop_bulk_and_quick_edit_column_<?php echo $column_name; ?>_label"><?php _e($attribute_def->frontend_label, 'wpshop'); ?></span>
3256
		<?php echo str_replace('chosen_select', '', str_replace('alignleft', '', $input)); ?>
3257
	</div>
3258
<?php
3259
			}
3260
			break;
3261
		}
3262
	}
3263
3264
	/**
3265
	 * Define the different field available for bulk edition for entities. Attributes to display are defined by checking box in attribute option
3266
	 *
3267
	 * @param string $column_name The column name for output type definition
3268
	 * @param string $post_type The current
0 ignored issues
show
Bug introduced by
There is no parameter named $post_type. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

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

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

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

Loading history...
3269
	 *
3270
	 */
3271
	public static function bulk_edit( $column_name, $entity ) {
3272
		switch ( $entity ) {
3273
			case WPSHOP_NEWTYPE_IDENTIFIER_PRODUCT:
3274
				$attribute_def = wpshop_attributes::getElement($column_name, "'valid'", 'code');
3275
				if ( !empty($attribute_def) ) {
3276
					$input_def = self::get_attribute_field_definition( $attribute_def, '', array('input_class' => ' wpshop_bulk_and_quick_edit_input') );
3277
					$input = wpshop_form::check_input_type($input_def, $input_def['input_domain']);
3278
?>
3279
	<div class="wpshop_bulk_and_quick_edit_column_container wpshop_bulk_and_quick_edit_column_<?php echo $column_name; ?>_container">
3280
		<span class="wpshop_bulk_and_quick_edit_column_label wpshop_bulk_and_quick_edit_column_<?php echo $column_name; ?>_label"><?php _e($attribute_def->frontend_label, 'wpshop'); ?></span>
3281
		<?php echo str_replace('chosen_select', '', str_replace('alignleft', '', $input)); ?>
3282
		<!-- <input class="wpshop_bulk_and_quick_edit_input wpshop_bulk_and_quick_edit_input_data_type_<?php echo $attribute_def->data_type; ?> wpshop_bulk_and_quick_edit_input_data_code_<?php echo $attribute_def->code; ?>" type="text" name="<?php echo $entity; ?>_-code-_<?php echo $attribute_def->code; ?>" value="" />  -->
3283
	</div>
3284
<?php
3285
			}
3286
			break;
3287
		}
3288
	}
3289
3290
}
3291
3292
?>
3293