wpshop_attributes   F
last analyzed

Complexity

Total Complexity 706

Size/Duplication

Total Lines 3265
Duplicated Lines 10.35 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

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

40 Methods

Rating   Name   Duplication   Size   Complexity  
B getPageFormButton() 5 20 9
C getElement() 0 38 8
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 elementAction() 120 446 152
F elementEdition() 111 602 102
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 75 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

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']) ? $_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
		global $attribute_displayed_field, $attribute_options_group;
639
		$dbFieldList = wpshop_database::fields_to_input(self::getDbTable());
640
		$editedItem = '';
641
		if($itemToEdit != '')
642
			$editedItem = self::getElement($itemToEdit);
643
644
		$the_form_content_hidden = $the_form_general_content = '';
645
		$the_form_option_content_list = array();
646
		foreach($dbFieldList as $input_key => $input_def){
647
648
			if(!isset($attribute_displayed_field) || !is_array($attribute_displayed_field) || in_array($input_def['name'], $attribute_displayed_field)){
649
				$input_def['label'] = $input_def['name'];
650
				$input_def_id=$input_def['id']='wpshop_' . self::currentPageCode . '_edition_table_field_id_'.$input_def['label'];
651
652
				$pageAction = isset($_REQUEST[self::getDbTable() . '_action']) ? sanitize_text_field($_REQUEST[self::getDbTable() . '_action']) : '';
653
				$requestFormValue = isset($_REQUEST[self::currentPageCode][$input_def['label']]) ? sanitize_text_field($_REQUEST[self::currentPageCode][$input_def['label']]) : '';
654
				$currentFieldValue = $input_def['value'];
655 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...
656
					$currentFieldValue = $editedItem->{$input_def['label']};
657
				elseif(($pageAction != '') && ($requestFormValue != ''))
658
					$currentFieldValue = $requestFormValue;
659
660
				if($input_def['label'] == 'status'){
661 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...
662
						$key = array_keys($input_def['possible_value'], 'notused');
663
						unset($input_def['possible_value'][$key[0]]);
664
					}
665 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...
666
						$key = array_keys($input_def['possible_value'], 'dbl');
667
						unset($input_def['possible_value'][$key[0]]);
668
					}
669
670
					$input_def['type'] = 'checkbox';
671
					$input_def['label'] = __('Use this attribute', 'wpshop');
672
					$input_def['possible_value'] = array('valid');
673
					$input_def_id.='_valid';
674
					$input_def['options_label']['custom'] = '<a href="#" title="'.__('Check this box for using this attribute', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
675
				}
676
677
				if ( (substr($input_def['label'], 0, 3) == 'is_') || ( $input_def['label'] == '_display_informations_about_value') ) {
678
					$input_def['type'] = 'checkbox';
679
					$input_def['possible_value'] = 'yes';
680
				}
681
				switch($input_def['label']){
682 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...
683
						$input_def['options_label']['custom'] = '<a href="#" title="'.__('Check this box for using unit with this attribute', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
684
					break;
685 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...
686
						$input_def['options_label']['custom'] = '<a href="#" title="'.__('Check this box for displaying this attribute in shop', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
687
					break;
688 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...
689
						$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>';
690
					break;
691 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...
692
						$input_def['options_label']['custom'] = '<a href="#" title="'.__('Check this box for displaying this attribute into sortbar', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
693
					break;
694 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...
695
						$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>';
696
					break;
697 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...
698
						$input_def['options_label']['custom'] = '<a href="#" title="'.__('Check this box for using in advanced search form', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
699
					break;
700 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...
701
						$input_def['options_label']['custom'] = '<a href="#" title="'.__('Separate with a space each CSS Class', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
702
					break;
703 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...
704
						$input_def['options_label']['custom'] = '<a href="#" title="'.__('Separate with a space each CSS Class', 'wpshop').'" class="wpshop_infobulle_marker">?</a>';
705
					break;
706 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...
707
						$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>';
708
					break;
709 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...
710
						$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>';
711
					break;
712 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...
713
						$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>';
714
					break;
715 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...
716
						$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>';
717
					break;
718
					case 'is_used_in_variation':
719
						$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>';
720
						if ( !empty($editedItem) && ($editedItem->is_used_for_variation == 'yes') ) {
721
							$input_def['option'] = 'disabled="disabled"';
722
						}
723
					break;
724 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...
725
						$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>';
726
					break;
727
				}
728
729
				$input_def['value'] = $currentFieldValue;
730
				if($input_def['label'] == 'code')
731
					$input_def['type'] = 'hidden';
732
				elseif($input_def['label'] == 'entity_id'){
733
					$input_def['possible_value'] = wpshop_entities::get_entities_list();
734
					$input_def['valueToPut'] = 'index';
735
					$input_def['type'] = 'select';
736
737
					$i=0;
738
					foreach($input_def['possible_value'] as $entity_id => $entity_name) {
739
						if($i <= 0){
740
							$current_entity_id = $entity_id;
741
						}
742
						$i++;
743
					}
744
				}
745
				elseif($input_def['label'] == '_unit_group_id'){
746
					$input_def['possible_value'] = wpshop_attributes_unit::get_unit_group();
747
					$input_def['type'] = 'select';
748
				}
749
				elseif($input_def['label'] == '_default_unit'){
750
					$unit_group_list = wpshop_attributes_unit::get_unit_group();
751
					$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:''));
752
					$input_def['type'] = 'select';
753
				}
754
				elseif ($input_def['label'] == 'backend_input') {
755
					if ( !is_object($editedItem) ) {
756
						$input_def['type'] = 'hidden';
757
					}
758
					else {
759
						$new_possible_value = array();
760 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...
761
							case 'integer':
762
								$new_possible_value[__('Checkbox', 'wpshop')] = 'checkbox';
763
								$new_possible_value[__('Radio button', 'wpshop')] = 'radio';
764
								$new_possible_value[__('select', 'wpshop')] = 'select';
765
								$new_possible_value[__('multiple-select', 'wpshop')] = 'multiple-select';
766
								break;
767
							case 'varchar':
768
								switch ( $input_def['value'] ) {
769
									case 'hidden':
770
										$new_possible_value[__('Hidden field', 'wpshop')] = 'hidden_field';
771
										break;
772
									case 'password':
773
										$new_possible_value[__('Password field', 'wpshop')] = 'pass_field';
774
										break;
775
									default:
776
										$new_possible_value[__('Text field', 'wpshop')] = 'short_text';
777
										break;
778
								}
779
								break;
780
							case 'text':
781
								$new_possible_value[__('Textarea field', 'wpshop')] = 'textarea';
782
								break;
783
							case 'decimal':
784
								$new_possible_value[__('Number field', 'wpshop')] = 'float_field';
785
								break;
786
							case 'datetime':
787
								$new_possible_value[__('Date field', 'wpshop')] = 'date_field';
788
								break;
789
						}
790
						$input_def['possible_value'] = $new_possible_value;
791
					}
792
				}
793
				elseif ($input_def['label'] == 'frontend_input') {
794
					$new_possible_value = array();
795
796
					if ( is_object($editedItem) ) {
797 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...
798
							case 'integer':
799
								$new_possible_value[__('Checkbox', 'wpshop')] = 'checkbox';
800
								$new_possible_value[__('Radio button', 'wpshop')] = 'radio';
801
								$new_possible_value[__('select', 'wpshop')] = 'select';
802
								$new_possible_value[__('multiple-select', 'wpshop')] = 'multiple-select';
803
								break;
804
							case 'varchar':
805
									switch ( $input_def['value'] ) {
806
										case 'hidden':
807
											$new_possible_value[__('Hidden field', 'wpshop')] = 'hidden_field';
808
										break;
809
										case 'password':
810
											$new_possible_value[__('Password field', 'wpshop')] = 'pass_field';
811
										break;
812
										default:
813
											$new_possible_value[__('Text field', 'wpshop')] = 'short_text';
814
										break;
815
									}
816
								break;
817
							case 'text':
818
									$new_possible_value[__('Textarea field', 'wpshop')] = 'textarea';
819
								break;
820
							case 'decimal':
821
									$new_possible_value[__('Number field', 'wpshop')] = 'float_field';
822
								break;
823
							case 'datetime':
824
									$new_possible_value[__('Date field', 'wpshop')] = 'date_field';
825
								break;
826
						}
827
					}
828
					else {
829
						$new_possible_value[__('Text field', 'wpshop')] = 'short_text';
830
						$new_possible_value[__('Number field', 'wpshop')] = 'float_field';
831
						$new_possible_value[__('Date field', 'wpshop')] = 'date_field';
832
						$new_possible_value[__('Textarea field', 'wpshop')] = 'textarea';
833
						$new_possible_value[__('Password field', 'wpshop')] = 'pass_field';
834
						$new_possible_value[__('Hidden field', 'wpshop')] = 'hidden_field';
835
						$new_possible_value[__('Checkbox', 'wpshop')] = 'checkbox';
836
						$new_possible_value[__('Radio button', 'wpshop')] = 'radio';
837
						$new_possible_value[__('select', 'wpshop')] = 'select';
838
						$new_possible_value[__('multiple-select', 'wpshop')] = 'multiple-select';
839
					}
840
841
					$input_def['possible_value'] = $new_possible_value;
842
843
					if ( !empty($editedItem->frontend_input) ) {
844
						switch ( $editedItem->frontend_input ) {
845
							case 'text':
846
								switch ( $editedItem->data_type ) {
847
									case 'varchar':
848
										$input_def['value'] = 'short_text';
849
									break;
850
									case 'decimal':
851
										$input_def['value'] = 'float_field';
852
									break;
853
									case 'datetime':
854
										$input_def['value'] = 'date_field';
855
									break;
856
									case 'hidden':
857
										$input_def['value'] = 'hidden_field';
858
									break;
859
									case 'password':
860
										$input_def['value'] = 'pass_field';
861
									break;
862
								}
863
							break;
864
							default:
865
								$input_def['value'] = $editedItem->frontend_input;
866
							break;
867
						}
868
					}
869
				}
870
871
				if(is_object($editedItem) && (($input_def['label'] == 'code') || ($input_def['label'] == 'data_type') || ($input_def['label'] == 'entity_id'))){
872
					// $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...
873
					$input_def['option'] = ' disabled="disabled" ';
874
					$the_form_content_hidden .= '<input type="hidden" name="' . self::getDbTable() . '[' . $input_def['name'] . ']" value="' . $input_def['value'] . '" />';
875
					$input_def['label'] = $input_def['name'];
876
					$input_def['name'] = $input_def['name'] . '_already_defined';
877
				}
878
879
				$input_def['value'] = str_replace("\\", "", $input_def['value']);
880
881
				$the_input = wpshop_form::check_input_type($input_def, self::getDbTable());
882
				if ( $input_def['label'] == 'default_value' ) {
883
					if ( !empty($editedItem->frontend_input) ) {
884
						switch ( $editedItem->frontend_input ) {
885
							case 'text':
886
								$input_def['type'] = 'text';
887
								switch ( $editedItem->data_type ) {
888
									case 'datetime':
889
										$the_input = wpshop_attributes::attribute_type_date_config( unserialize($input_def['value']) );
890
891
										$input_def['label'] = __('Date field configuration','wpshop');
892
									break;
893
									default:
894
										$the_input = wpshop_form::check_input_type($input_def, WPSHOP_DBT_ATTRIBUTE);
895
									break;
896
								}
897
							break;
898
							case 'hidden':
899
									$the_input = '';
900
								break;
901
							case 'password':
902
									$the_input = '';
903
								break;
904
							case 'select':
905
							case 'multiple-select':
906
							case 'radio':
907
							case 'checkbox':
908
								$input_def['label'] = __('Options list for attribute','wpshop') . '
909
<div class="alignright wpshop_change_select_data_type" >
910
	+' . __('Change data type for this attribute', 'wpshop') . '
911
</div>';
912
								$the_input = wpshop_attributes::get_select_options_list($itemToEdit, $editedItem->data_type_to_use);
913
914
								break;
915
							case 'textarea':
916
								$input_def['type'] = 'textarea';
917
								$the_input = wpshop_form::check_input_type($input_def, WPSHOP_DBT_ATTRIBUTE);
918
							break;
919
						}
920
					}
921
					else {
922
						$input_def['type']='text';
923
						$the_input = wpshop_form::check_input_type($input_def, self::getDbTable());
924
					}
925
				}
926
				if( $input_def['label'] == '_unit_group_id') {
927
					$the_input .= '<div id="wpshop_loader_input_group_unit"></div>';
928
					$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>';
929
				}
930
931
				if( $input_def['label'] == '_default_unit') {
932
					$the_input .= '<div id="wpshop_loader_input_unit"></div>';
933
					$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>';
934
					$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") . '" />';
935
					$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>';
936
				}
937
938
939
				if($input_def['type'] != 'hidden'){
940
					if ( ($input_def['label'] == 'entity_id') && is_object($editedItem) ) {
941
						$the_input .= '<br/><span class="wpshop_duplicate_attribute" >' . __('Duplicate this attribute to . another entity', 'wpshop') . '</span>';
942
					}
943
					$input = '
944
		<tr class="wpshop_' . self::currentPageCode . '_edition_table_line wpshop_' . self::currentPageCode . '_edition_table_line_'.$input_def['name'].'" >
945
			<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>
946
			<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>
947
		</tr>';
948
					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 )) )
949
						$the_form_option_content_list[$input_def['label']] = $input;
950
					else {
951
						$the_form_general_content .= $input;
952
						if ( ($input_def['label'] == 'frontend_input') && !is_object($editedItem) ) {
953
954
							$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...
955
956
							$input = '
957
		<tr class="wpshop_' . self::currentPageCode . '_edition_table_line wpshop_' . self::currentPageCode . '_edition_table_line_set_section" >
958
			<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>
959
			<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>
960
		</tr>';
961
							$the_form_general_content .= $input;
962
						}
963
					}
964
				}
965
				else{
966
					$the_form_content_hidden .= '
967
				' . $the_input;
968
				}
969
			}
970
		}
971
972
973
974
975
976
		$section_legend = '';
977
		$section_page_code = self::currentPageCode;
978
		$section_content = $the_form_general_content;
979
980
		ob_start();
981
		include(WPSHOP_TEMPLATES_DIR.'admin/admin_box_section.tpl.php');
982
		$the_form_general_content = ob_get_contents();
983
		ob_end_clean();
984
985
		/** It is attribute TVA, add a button to calcilate price in mass **/
986
		if ( !empty($editedItem) && !empty($editedItem->code) && $editedItem->code == 'tx_tva' ) {
987
			$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/>';
988
			$the_form_general_content .= __('If you have updated your VAT rates, save it and update your products price after', 'wpshop' );
989
		}
990
		if (!empty($the_form_option_content_list)) {
991
			$the_form_option_content_section='';
992
			foreach ($attribute_options_group as $group_name => $group_content) {
993
				$section_content = '';
994
				foreach ($group_content as $group_code) {
995
					if (array_key_exists($group_code, $the_form_option_content_list)) {
996
						$section_content .= $the_form_option_content_list[$group_code];
997
						unset($the_form_option_content_list[$group_code]);
998
					}
999
				}
1000
				$section_legend = __($group_name,'wpshop');
1001
				$section_page_code = self::currentPageCode;
1002
1003
				ob_start();
1004
				include(WPSHOP_TEMPLATES_DIR.'admin/admin_box_section.tpl.php');
1005
				$the_form_option_content_section .= ob_get_contents();
1006
				ob_end_clean();
1007
			}
1008
1009
			/*	Check there are other attributes to display not in defined group	*/
1010
			if (!empty($the_form_option_content_list)) {
1011
				$section_legend = __('General options','wpshop');
1012
				$section_content = implode('', $the_form_option_content_list);
1013
				$section_page_code = self::currentPageCode;
1014
1015
				ob_start();
1016
				include(WPSHOP_TEMPLATES_DIR.'admin/admin_box_section.tpl.php');
1017
				$the_form_option_content = ob_get_contents();
1018
				ob_end_clean();
1019
1020
				$the_form_option_content .= $the_form_option_content_section;
1021
			}
1022
1023
		}
1024
1025
		/*	Default content for the current page	*/
1026
		$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...
1027
		$bloc_list[self::currentPageCode]['main_info']['content'] = $the_form_general_content;
1028
1029
		$bloc_list[self::currentPageCode]['options']['title']=__('Options', 'wpshop');
1030
		$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...
1031
1032
		$action = !empty( $_REQUEST['action'] ) ? sanitize_text_field( $_REQUEST['action' ] ) : '';
1033
		$the_form = '
1034
<form name="' . self::getDbTable() . '_form" id="' . self::getDbTable() . '_form" method="post" action="#" >
1035
	' . wpshop_form::form_input(self::getDbTable() . '_action', self::getDbTable() . '_action', (isset($action) && ($action != '') ? sanitize_text_field($action) : 'save') , 'hidden') . '
1036
	' . 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) . '
1037
</form>
1038
<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>';
1039
		$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 646. 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...
1040
		unset($input_def['possible_value'][$current_entity_id]);
1041
		$input_def['valueToPut'] = 'index';
1042
		$input_def['type'] = 'select';
1043
		$input_def['name'] = 'wpshop_entity_to_duplicate_to';
1044
		$input_def['id'] = 'wpshop_entity_to_duplicate_to';
1045
		$the_form .= '
1046
<div title="' . __('Duplicate attribute to another entity', 'wpshop') . '" id="wpshop_dialog_duplicate_attribute" >
1047
	' . __('Choose an entity to copy the selected attribute to', 'wpshop') . '
1048
	' . wpshop_form::check_input_type($input_def) . '
1049
</div>';
1050
1051
		$the_form .= '
1052
<script type="text/javascript" >
1053
	wpshop(document).ready(function(){
1054
		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') . '");
1055
1056
		jQuery("#wpshop_dialog_duplicate_attribute").dialog({
1057
			autoOpen: false,
1058
			width: 500,
1059
			height: 100,
1060
			modal: true,
1061
			dialogClass: "wpshop_uidialog_box",
1062
			resizable: false,
1063
			buttons:{
1064
				"'.__('Duplicate', 'wpshop').'": function(){
1065
					var data = {
1066
						action: "wpshop_duplicate_attribute",
1067
						wpshop_ajax_nonce: "' . wp_create_nonce("wpshop_duplicate_attribute") . '",
1068
						attribute_id: jQuery("#wpshop_attributes_edition_table_field_id_id").val(),
1069
						entity: jQuery("#wpshop_entity_to_duplicate_to").val()
1070
					};
1071
					jQuery.post(ajaxurl, data, function(response) {
1072
						if (response[0]) {
1073
							jQuery("#wpshop_dialog_duplicate_attribute").append(response[1]);
1074
						}
1075
						else {
1076
							alert(response[1]);
1077
						}
1078
					}, "json");
1079
				},
1080
				"'.__('Cancel', 'wpshop').'": function(){
1081
					jQuery(this).dialog("close");
1082
					jQuery(".wpshop_duplicate_attribute_result").remove();
1083
				}
1084
			}
1085
		});
1086
		jQuery(".wpshop_duplicate_attribute").live("click", function(){
1087
			jQuery("#wpshop_dialog_duplicate_attribute").dialog("open");
1088
		});
1089
1090
		jQuery("#wpshop_dialog_change_select_data_type").dialog({
1091
			autoOpen: false,
1092
			width: 800,
1093
			height: 200,
1094
			modal: true,
1095
			dialogClass: "wpshop_uidialog_box",
1096
			resizable: false,
1097
			buttons:{
1098
				"'.__('Change type', 'wpshop').'": function(){
1099
					var delete_entity = false;
1100
					if(jQuery("#delete_entity").is(":checked")){
1101
						var delete_entity = true;
1102
					}
1103
					var delete_items_of_entity = false;
1104
					if(jQuery("#delete_items_of_entity").is(":checked")){
1105
						var delete_items_of_entity = true;
1106
					}
1107
					var data = {
1108
						action: "attribute_select_data_type_change",
1109
						wpshop_ajax_nonce: "' . wp_create_nonce("wpshop_attribute_change_select_data_type_change") . '",
1110
						attribute_id: jQuery("#wpshop_attributes_edition_table_field_id_id").val(),
1111
						internal_data: jQuery("#internal_data").val(),
1112
						data_type: jQuery("#wpshop_attribute_change_data_type_new_type").val(),
1113
						delete_entity: delete_entity,
1114
						delete_items_of_entity: delete_items_of_entity
1115
					};
1116
					jQuery.post(ajaxurl, data, function(response) {
1117
						jQuery(".wpshop_attributes_edition_table_field_input_default_value").html( response );
1118
						jQuery("#wpshop_dialog_change_select_data_type").dialog("close");
1119
					}, "json");
1120
				},
1121
				"'.__('Cancel', 'wpshop').'": function(){
1122
					jQuery(this).dialog("close");
1123
				}
1124
			}
1125
		});
1126
1127
		jQuery(".wpshop_attribute_change_select_data_type_deletion_input").live("click",function() {
1128
			var display = false;
1129
			if (jQuery(".wpshop_attribute_change_select_data_type_deletion_input_item").is(":checked") ) {
1130
				display = true;
1131
			}
1132
			if (jQuery(".wpshop_attribute_change_select_data_type_deletion_input_entity").is(":checked") ) {
1133
				display = true;
1134
			}
1135
			if (display) {
1136
				jQuery(".wpshop_attribute_change_data_type_alert").show();
1137
			}
1138
			else {
1139
				jQuery(".wpshop_attribute_change_data_type_alert").hide();
1140
			}
1141
		});
1142
1143
		jQuery(".wpshop_change_select_data_type").live("click",function(){
1144
			jQuery("#wpshop_dialog_change_select_data_type_container").html(jQuery("#wpshopLoadingPicture").html());
1145
			jQuery("#wpshop_dialog_change_select_data_type").dialog("open");
1146
1147
			var data = {
1148
				action: "attribute_select_data_type",
1149
				current_attribute: jQuery("#wpshop_attributes_edition_table_field_id_id").val(),
1150
				wpshop_ajax_nonce: "' . wp_create_nonce("wpshop_attribute_change_select_data_type") . '"
1151
			};
1152
			jQuery.post(ajaxurl, data, function(response) {
1153
				jQuery("#wpshop_dialog_change_select_data_type_container").html( response );
1154
			}, "json");
1155
1156
		});
1157
		jQuery("#wpshop_attributes_edition_table_field_id__unit_group_id").change(function(){
1158
			change_unit_list();
1159
		});';
1160
1161
		if ( !is_object($editedItem) )  {
1162
			$the_form .= '
1163
		jQuery("#wpshop_attributes_edition_table_field_id_frontend_input").change(function(){
1164
			jQuery(".wpshop_attributes_edition_table_field_input_default_value").html(jQuery("#wpshopLoadingPicture").html());
1165
1166
			var data = {
1167
				action: "attribute_output_type",
1168
				current_type: jQuery(this).val(),
1169
				wpshop_ajax_nonce: "' . wp_create_nonce("wpshop_attribute_output_type_selection") . '"
1170
			};
1171
			jQuery.post(ajaxurl, data, function(response) {
1172
				jQuery(".wpshop_attributes_edition_table_field_input_default_value").html((response[0]));
1173
				jQuery(".wpshop_attributes_edition_table_field_label_default_value label").html((response[1]));
1174
			}, "json");
1175
1176
// 			var data = {
1177
// 				action: "attribute_frontend_input_type",
1178
// 				current_type: jQuery(this).val(),
1179
// 				wpshop_ajax_nonce: "' . wp_create_nonce("wpshop_attribute_frontend_input_type") . '"
1180
// 			};
1181
// 			jQuery.getJSON(ajaxurl, data, function(response) {
1182
// 				jQuery("#wpshop_attributes_edition_table_field_id_frontend_input").html(response);
1183
// 			});
1184
1185
		});';
1186
		}
1187
1188
		$the_form .= '
1189
			jQuery("#wpshop_attributes_edition_table_field_id_entity_id").change(function(){
1190
			jQuery(".wpshop_attributes_edition_table_field_input_set_section").html(jQuery("#wpshopLoadingPicture").html());
1191
1192
			var data = {
1193
				action: "attribute_entity_set_selection",
1194
				current_entity_id: jQuery(this).val(),
1195
				wpshop_ajax_nonce: "' . wp_create_nonce("wpshop_attribute_entity_set_selection") . '"
1196
			};
1197
			jQuery.post(ajaxurl, data, function(response) {
1198
				jQuery(".wpshop_attributes_edition_table_field_input_set_section").html( response );
1199
			}, "json");
1200
		});
1201
1202
1203
		jQuery("#wpshop_attributes_edition_table_field_id_is_used_for_variation").click(function(){
1204
			if ( jQuery(this).is(":checked") ) {
1205
				jQuery("#wpshop_attributes_edition_table_field_id_is_used_in_variation").prop("checked", false);
1206
				jQuery("#wpshop_attributes_edition_table_field_id_is_used_in_variation").prop("disabled", true);
1207
			}
1208
			else {
1209
				jQuery("#wpshop_attributes_edition_table_field_id_is_used_in_variation").prop("disabled", false);
1210
			}
1211
		});
1212
	});
1213
	function change_unit_list(){
1214
		var data = {
1215
					action: "load_attribute_unit_list",
1216
					wpshop_ajax_nonce: jQuery("#input_wpshop_load_attribute_unit_list").val(),
1217
					current_group: jQuery("#wpshop_attributes_edition_table_field_id__unit_group_id").val(),
1218
					selected_list:"unit"
1219
				};
1220
			//Response, update the combo box
1221
				jQuery.post(ajaxurl, data, function(response) {
1222
					if ( response[0] ) {
1223
						jQuery("#wpshop_attributes_edition_table_field_id__default_unit").html(response[1]);
1224
					}
1225
					else {
1226
						alert( response[1] );
1227
					}
1228
				}, "json");
1229
1230
	}
1231
</script>';
1232
1233
1234
1235
1236
1237
		return $the_form;
1238
	}
1239
	/**
1240
	 *	Return the different button to save the item currently being added or edited
1241
	 *
1242
	 *	@return string $currentPageButton The html output code with the different button to add to the interface
1243
	 */
1244
	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...
1245
		$action = isset($_REQUEST['action']) ? sanitize_text_field($_REQUEST['action']) : 'add';
1246
		$currentPageButton = '';
1247
1248
		 //$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...
1249
1250 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...
1251
			$currentPageButton .= '<input type="button" class="button-primary" id="add" name="add" value="' . __('Add', 'wpshop') . '" />';
1252
1253
		elseif(current_user_can('wpshop_edit_attributes'))
1254
		$currentPageButton .= '<input type="button" class="button-primary" id="save" name="save" value="' . __('Save', 'wpshop') . '" />';
1255
1256
		$attribute_undeletable = unserialize(WPSHOP_ATTRIBUTE_UNDELETABLE);
1257
		$attribute = self::getElement($element_id, "'valid', 'moderated', 'notused'", 'id');
1258
		$attribute_code = !empty($attribute->code)?$attribute->code:'';
1259
		if(current_user_can('wpshop_delete_attributes') && ($action != 'add') && !in_array($attribute_code, $attribute_undeletable))
1260
			$currentPageButton .= '<input type="button" class="button-secondary wpshop_delete_element_button wpshop_delete_element_button_'.self::currentPageCode.'" id="delete" name="delete" value="' . __('Delete', 'wpshop') . '" />';
1261
1262
		return $currentPageButton;
1263
	}
1264
1265
	/**
1266
	 *	Get the existing attribute list into database
1267
	 *
1268
	 *	@param integer $element_id optionnal The attribute identifier we want to get. If not specify the entire list will be returned
1269
	 *	@param string $element_status optionnal The status of element to get into database. Default is set to valid element
1270
	 *	@param mixed $field_to_search optionnal The field we want to check the row identifier into. Default is to set id
1271
	 *
1272
	 *	@return object $element_list A wordpress database object containing the attribute list
1273
	 */
1274
	public static function getElement($element_id = '', $element_status = "'valid', 'moderated', 'notused'", $field_to_search = 'id', $list = false){
1275
1276
		global $wpdb;
1277
		$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...
1278
		$moreQuery = "";
1279
		$moreArgs = array( 1, );
1280
1281
		$orderby = !empty( $_REQUEST['orderby'] ) ? sanitize_text_field( $_REQUEST['orderby'] ) : '';
1282
		$order = !empty( $_REQUEST['order'] ) ? sanitize_text_field( $_REQUEST['order'] ) : '';
1283
1284
		if($element_id != ''){
1285
			$moreQuery .= "
1286
					AND CURRENT_ELEMENT." . $field_to_search . " = %s ";
1287
			$moreArgs[] = $element_id;
1288
		}
1289
		if(!empty($orderby) && !empty($order)){
1290
			$moreQuery .= "
1291
					ORDER BY " . $orderby . "  " . $order;
1292
		}
1293
1294
		$query = $wpdb->prepare(
1295
			"SELECT CURRENT_ELEMENT.*, ENTITIES.post_name as entity
1296
			FROM " . self::getDbTable() . " AS CURRENT_ELEMENT
1297
			INNER JOIN {$wpdb->posts} AS ENTITIES ON (ENTITIES.ID = CURRENT_ELEMENT.entity_id)
1298
			WHERE %d AND CURRENT_ELEMENT.status IN (".$element_status.") " . $moreQuery,
1299
			$moreArgs
1300
		);
1301
1302
		/*	Get the query result regarding on the function parameters. If there must be only one result or a collection	*/
1303
		if(($element_id == '') || $list){
1304
			$element_list = $wpdb->get_results($query);
1305
		}
1306
		else{
1307
			$element_list = $wpdb->get_row($query);
1308
		}
1309
1310
		return $element_list;
1311
	}
1312
1313
	/**
1314
	 *	Save the different value for attribute of a given entity type and entity
1315
	 *
1316
	 *	@param array $attributeToSet The list of attribute with each value to set like this : ['integer']['tx_tva'] = 10
1317
	 *	@param integer $entityTypeId The entity type identifier (products/categories/...)
1318
	 *	@param integer $entityId The entity identifier we want to save attribute for (The specific product/category/...)
1319
	 *	@param string $language The language to set the value for into database
1320
	 *
1321
	 */
1322
	public static function saveAttributeForEntity($attributeToSet, $entityTypeId, $entityId, $language = WPSHOP_CURRENT_LOCALE, $from = '') {
1323
		global $wpdb;
1324
		/* Recuperation de l'identifiant de l'utilisateur connecte */
1325
		$user_id = function_exists('is_user_logged_in') && is_user_logged_in() ? get_current_user_id() : '0';
1326
		$sent_attribute_list = array();
1327
1328
		if ( !empty($attributeToSet) ) {
1329
			$attributeToSet = apply_filters( 'save_attribute_for_entity', $attributeToSet, $entityTypeId, $entityId );
1330
			$old_attribute_to_set = $attributeToSet;
1331
			$attribute_setted = array();
1332
			foreach ($attributeToSet as $attributeType => $attributeTypeDetails) {
1333
				/** 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 */
1334
				$delete_current_attribute_values_params = array(
1335
					'entity_id' => $entityId,
1336
					'entity_type_id' => $entityTypeId
1337
				);
1338
				if ( WPSHOP_ATTRIBUTE_VALUE_PER_USER ) {
1339
					$delete_current_attribute_values_params['user_id'] = $user_id;
1340
				}
1341
1342
				if(!empty($attributeTypeDetails) && is_array($attributeTypeDetails)) {
1343
					$attributeTypeDetails = apply_filters( "save_attribute_for_entity_{$attributeType}", $attributeTypeDetails, $entityTypeId, $entityId );
1344
					foreach($attributeTypeDetails as $attribute_code => $attributeValue) {
1345
						$attributeValue = apply_filters( "save_attribute_for_entity_{$attributeType}_{$attribute_code}", apply_filters( "save_attribute_for_entity__{$attribute_code}", $attributeValue, $entityTypeId, $entityId ), $entityTypeId, $entityId );
1346
						$old_attribute_value = $attributeValue;
1347
1348
						if ( $attributeType == 'decimal' ) {
1349
							$attributeValue = str_replace(',', '.', $attributeValue);
1350
						}
1351
						if ( ($attributeType == 'integer') && !is_array($attributeValue) ) {
1352
							$attributeValue = (int)$attributeValue;
1353
						}
1354
						$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...
1355
						if($attribute_code != 'unit') {
1356
1357
							$unit_id = 0;
1358
							if(isset($attributeTypeDetails['unit'][$attribute_code])){
1359
								$unit_id = $attributeTypeDetails['unit'][$attribute_code];
1360
							}
1361
1362
							$currentAttribute = self::getElement($attribute_code, "'valid'", 'code');
1363
							if( !empty($currentAttribute) ){
1364
								$sent_attribute_list[] = $currentAttribute->id;
1365
1366
								/*	Enregistrement de la valeur actuelle de l'attribut dans la table d'historique si l'option historique est activee sur l'attribut courant	*/
1367
								if (  $currentAttribute->is_historisable == 'yes') {
1368
									$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);
1369
									$attribute_histo = $wpdb->get_results($query);
1370
									if(!empty($attribute_histo)){
1371
										$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...
1372
										$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...
1373
										$attribute_histo_content['creation_date_value'] = $attribute_histo[0]->creation_date_value;
1374
										$attribute_histo_content['original_value_id'] = $attribute_histo[0]->value_id;
1375
										$attribute_histo_content['entity_type_id'] = $attribute_histo[0]->entity_type_id;
1376
										$attribute_histo_content['attribute_id'] = $attribute_histo[0]->attribute_id;
1377
										$attribute_histo_content['entity_id'] = $attribute_histo[0]->entity_id;
1378
										$attribute_histo_content['unit_id'] = $attribute_histo[0]->unit_id;
1379
										$attribute_histo_content['user_id'] = $attribute_histo[0]->user_id;
1380
										$attribute_histo_content['language'] = $attribute_histo[0]->language;
1381
										$attribute_histo_content['value'] = $attribute_histo[0]->value;
1382
										$attribute_histo_content['value_type'] = WPSHOP_DBT_ATTRIBUTE_VALUES_PREFIX . $attributeType;
1383
										$wpdb->insert(WPSHOP_DBT_ATTRIBUTE_VALUES_HISTO, $attribute_histo_content);
1384
									}
1385
								}
1386
								$attributeValue = str_replace("\\", "", $attributeValue);
1387
1388
								if ( empty($from) || (!empty($attributeValue)) ) {
1389
									$wpdb->delete(WPSHOP_DBT_ATTRIBUTE_VALUES_PREFIX.$attributeType, array_merge($delete_current_attribute_values_params, array('attribute_id' => $currentAttribute->id)));
1390
1391
									/**	Insertion de la nouvelle valeur de l'attribut dans la base	*/
1392
									$query_params = array(
1393
										'value_id' => '',
1394
										'entity_type_id' => $entityTypeId,
1395
										'attribute_id' => $currentAttribute->id,
1396
										'entity_id' => $entityId,
1397
										'unit_id' => $unit_id,
1398
										'language' => $language,
1399
										'user_id' => $user_id,
1400
										'creation_date_value' => current_time('mysql', 0)
1401
									);
1402
									/**	Si l'attribut courant est contenu dans un tableau (exemple: select multiple) on lit tout le tableau et on enregistre chaque valeur separement	*/
1403
									if(is_array($attributeValue)){
1404
										foreach($attributeValue as $a){
1405
											$wpdb->insert(WPSHOP_DBT_ATTRIBUTE_VALUES_PREFIX.$attributeType, array_merge($query_params, array('value' => $a)));
1406
										}
1407
									}
1408
									else{
1409
										$wpdb->insert(WPSHOP_DBT_ATTRIBUTE_VALUES_PREFIX.$attributeType, array_merge($query_params, array('value' => $attributeValue)));
1410
										\eoxia\log_class::exec( 'wpshop_attributes', 'wpshop_attributes', __( 'Add the attribute : ' . $currentAttribute->code . ' with value : ' . $attributeValue , 'wpshop' ), array( 'object_id' 	=> $entityId ), 0 );
1411
									}
1412
1413
									/**	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	*/
1414
									if ( ( ($currentAttribute->is_used_for_sort_by == 'yes') || ($currentAttribute->is_searchable == 'yes'))  || ( $currentAttribute->is_filterable == 'yes') && !empty($attributeValue) ) :
1415
										update_post_meta($entityId, '_'.$attribute_code, $attributeValue);
1416
									endif;
1417
1418
									/**	Enregistrement de toutes les valeurs des attributs dans une meta du produit	*/
1419
									$attribute_option = (!empty($_POST['attribute_option'][$attribute_code])) ? (array) $_POST['attribute_option'][$attribute_code] : null;
1420
									if (isset($attribute_option)) {
1421
										$value = self::get_attribute_type_select_option_info($attributeTypeDetails[$attribute_code], 'value');
1422
										if (strtolower($value) == 'yes') :
1423
											update_post_meta($entityId, 'attribute_option_'.$attribute_code, $attribute_option);
1424
										else :
1425
											delete_post_meta($entityId, 'attribute_option_'.$attribute_code);
1426
										endif;
1427
									}
1428
								}
1429
							}
1430
						}
1431
						do_action( "saved_attribute_for_entity_{$attributeType}_{$attribute_code}", $attributeValue, $old_attribute_value, $entityTypeId, $entityId );
1432
						do_action( "saved_attribute_for_entity__{$attribute_code}", $attributeValue, $old_attribute_value, $entityTypeId, $entityId );
1433
						if ( isset( $attribute_setted[$attributeType][$attribute_code] ) ) {
1434
							if( is_array( $attribute_setted[$attributeType][$attribute_code] )) {
1435
								$attribute_setted[$attributeType][$attribute_code][] = $attributeValue;
1436
							} else {
1437
								$attribute_setted[$attributeType][$attribute_code] = array( $attribute_setted[$attributeType][$attribute_code], $attributeValue );
1438
							}
1439
						} else {
1440
							$attribute_setted[$attributeType][$attribute_code] = $attributeValue;
1441
						}
1442
					}
1443
1444
					if ( empty($from) ) {
1445
						$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);
1446
						$attr_to_delete = $wpdb->get_results($query);
1447
						if(!empty($attr_to_delete)){
1448
							foreach ($attr_to_delete as $value) {
1449
								$wpdb->delete(WPSHOP_DBT_ATTRIBUTE_VALUES_PREFIX.$attributeType, array_merge($delete_current_attribute_values_params, array('value_id' => $value->value_id)));
1450
								\eoxia\log_class::exec( 'wpshop_attributes', 'wpshop_attributes', __( 'Remove the attribute : ' . $value->value_id, 'wpshop' ), array( 'object_id' 	=> $entityId ), 0 );
1451
							}
1452
						}
1453
					}
1454
				}
1455
			}
1456
			do_action( "saved_attribute_for_entity", $attribute_setted, $old_attribute_to_set, $entityTypeId, $entityId );
1457
		}
1458
	}
1459
1460
	/**
1461
	 *	Return the value for a given attribute of a given entity type and a given entity
1462
	 *
1463
	 *	@param string $attributeType The extension of the database table to get the attribute value in
1464
	 *	@param integer $attributeId The attribute identifier we want to get the value for
1465
	 *	@param integer $entityTypeId The entity type identifier we want to get the attribute value for (example: product = 1)
1466
	 	*	@param integer $entityId The entity id we want the attribute value for
1467
	 *
1468
	 *	@return object $attributeValue A wordpress database object containing the value of the attribute for the selected entity
1469
	 */
1470
	public static function getAttributeValueForEntityInSet($attributeType, $attributeId, $entityTypeId, $entityId, $atribute_params = array()) {
1471
		global $wpdb;
1472
		$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...
1473
1474
		$query_params = "";
1475
		$query_params_values = array($attributeId, $entityTypeId, $entityId);
1476
		if(WPSHOP_ATTRIBUTE_VALUE_PER_USER && (isset($atribute_params['intrinsic']) && ($atribute_params['intrinsic'] != 'yes'))){
1477
			$query_params = "
1478
				AND ATTR_VAL.user_id = %d";
1479
			$query_params_values[] = get_current_user_id();
1480
		}
1481
		$query = $wpdb->prepare(
1482
			"SELECT ATTR_VAL.value, ATTR_VAL.unit_id, ATTR_VAL.user_id
1483
			FROM " . WPSHOP_DBT_ATTRIBUTE_VALUES_PREFIX . $attributeType . " AS ATTR_VAL
1484
			WHERE ATTR_VAL.attribute_id = %d
1485
				AND ATTR_VAL.entity_type_id = %d
1486
				AND ATTR_VAL.entity_id = %d" . $query_params . "
1487
			ORDER BY ATTR_VAL.creation_date_value ASC",
1488
			$query_params_values
1489
		);
1490
		$attributeValue = $wpdb->get_results($query);
1491
1492
		if ( ( (count($attributeValue) <= 1 ) && !empty($attributeValue[0]) ) && ( empty($atribute_params['frontend_input']) || ($atribute_params['frontend_input'] != 'multiple-select') )) {
1493
			$attributeValue = $attributeValue[0];
1494
		}
1495
		else{
1496
			$entity_meta = get_post_meta($entityId, WPSHOP_PRODUCT_ATTRIBUTE_META_KEY, true);
1497
			if ( !empty($entity_meta) ) {
1498
				$query = $wpdb->prepare("SELECT code FROM " . WPSHOP_DBT_ATTRIBUTE . " WHERE id = %d AND entity_id = %d ", $attributeId, $entityTypeId);
1499
				$attribute_code = $wpdb->get_var($query);
1500
				$attributeValue = !empty($entity_meta[$attribute_code]) ? $entity_meta[$attribute_code] : null;
1501
			}
1502
			if ( is_array($attributeValue) ) {
1503
				$tmp_array = array();
1504
				if ( !empty($attributeValue) ) {
1505
					foreach ( $attributeValue as $att ) {
1506
						$obj = new stdClass();
1507
						$obj->value = $att;
1508
						$obj->unit_id = 0;
1509
						$obj->user_id = get_current_user_id();
1510
						$tmp_array[] = $obj;
1511
					}
1512
					$attributeValue = $tmp_array;
1513
				}
1514
			}
1515
		}
1516
// 		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...
1517
// 			$attributeValue = $attributeValue[0];
1518
// 		}
1519
1520
		return $attributeValue;
1521
	}
1522
1523
	/**
1524
	 *	Get the existing element list into database
1525
	 *
1526
	 *	@param integer $elementId optionnal The element identifier we want to get. If not specify the entire list will be returned
1527
	 *	@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...
1528
	 *
1529
	 *	@return object $elements A wordpress database object containing the element list
1530
	 */
1531
	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...
1532
		global $wpdb;
1533
		$elements = array();
1534
		$elementsWithAttributeAndValues = self::get_attribute_list_for_item($entityId, $elementId, $language);
1535
1536
		foreach ( $elementsWithAttributeAndValues as $elementDefinition ) {
1537
			$arrayKey = $elementDefinition->attribute_id;
1538
			if ( $keyForArray == 'code' ) {
1539
				$arrayKey = $elementDefinition->attribute_code;
1540
			}
1541
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['code'] = $elementDefinition->attribute_set_section_code;
1542
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['display_on_frontend'] = $elementDefinition->display_on_frontend;
1543
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['code'] = $elementDefinition->code;
1544
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['data_type'] = $elementDefinition->data_type;
1545
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['backend_table'] = $elementDefinition->backend_table;
1546
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['backend_input'] = $elementDefinition->backend_input;
1547
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['frontend_input'] = $elementDefinition->frontend_input;
1548
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['frontend_label'] = __( $elementDefinition->frontend_label, 'wpshop' );
1549
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['attribute_code'] = $elementDefinition->attribute_code;
1550
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['data_type_to_use'] = $elementDefinition->data_type_to_use;
1551
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['is_visible_in_front'] = $elementDefinition->is_visible_in_front;
1552
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['is_visible_in_front_listing'] = $elementDefinition->is_visible_in_front_listing;
1553
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['is_requiring_unit'] = $elementDefinition->is_requiring_unit;
1554
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['is_used_in_quick_add_form'] = $elementDefinition->is_used_in_quick_add_form;
1555
			$attributeValueField = 'attribute_value_' . $elementDefinition->data_type;
1556
1557
			// Manage the value differently if it is an array or not
1558
			if ( !empty($elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['value']) ) {
1559
				if (is_array($elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['value'])) {
1560
					$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['value'][] = $elementDefinition->$attributeValueField;
1561
				}
1562
				else {
1563
					$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['value'] = array($elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['value'],$elementDefinition->$attributeValueField);
1564
				}
1565
			}
1566
			else {
1567
				$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['value'] = $elementDefinition->$attributeValueField;
1568
			}
1569
1570
			if ( $elementDefinition->backend_input == 'multiple-select' ) {
1571
				$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['select_value'] = self::get_attribute_type_select_option_info($attributeValueField, 'value');
1572
			}
1573
1574
			$attributeUnitField = 'attribute_unit_' . $elementDefinition->data_type;
1575
			$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['unit'] = __( $elementDefinition->$attributeUnitField, 'wpshop' );
1576
			if( !empty($elementDefinition->is_requiring_unit ) && ( $elementDefinition->is_requiring_unit == 'yes' ) && empty( $elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['unit'] ) ) {
1577
				$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...
1578
				$query = $wpdb->prepare( 'SELECT unit FROM '. WPSHOP_DBT_ATTRIBUTE_UNIT . ' WHERE id = %d AND status = %s', $elementDefinition->_default_unit, 'valid');
1579
				$unit = $wpdb->get_var( $query );
1580
				$elements[$elementId][$elementDefinition->attribute_set_section_name]['attributes'][$arrayKey]['unit'] = __( $unit, 'wpshop' );
1581
			}
1582
1583
		}
1584
		return $elements;
1585
	}
1586
1587
	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...
1588
		global $wpdb;
1589
		$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...
1590
		$moreQuery = "";
1591
1592
		$entity_type = empty($defined_entity_type) ? get_post_type( $elementId ) : $defined_entity_type;
1593
1594
		$query = $wpdb->prepare(
1595
				"SELECT POST_META.*,
1596
					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,
1597
					ATTR_VALUE_VARCHAR.value AS attribute_value_varchar, ATTR_UNIT_VARCHAR.unit AS attribute_unit_varchar,
1598
					ATTR_VALUE_DECIMAL.value AS attribute_value_decimal, ATTR_UNIT_DECIMAL.unit AS attribute_unit_decimal,
1599
					ATTR_VALUE_TEXT.value AS attribute_value_text, ATTR_UNIT_TEXT.unit AS attribute_unit_text,
1600
					ATTR_VALUE_INTEGER.value AS attribute_value_integer, ATTR_UNIT_INTEGER.unit AS attribute_unit_integer,
1601
					ATTR_VALUE_DATETIME.value AS attribute_value_datetime, ATTR_UNIT_DATETIME.unit AS attribute_unit_datetime,
1602
					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
1603
				FROM " . WPSHOP_DBT_ATTRIBUTE . " AS ATTR
1604
					LEFT JOIN " . WPSHOP_DBT_ATTRIBUTE_DETAILS . " AS EAD ON (EAD.attribute_id = ATTR.id)
1605
					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))
1606
					LEFT JOIN " . WPSHOP_DBT_ATTRIBUTE_GROUP . " AS ATTRIBUTE_GROUP  ON (ATTRIBUTE_GROUP.id = EAD.attribute_group_id)
1607
					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) )
1608
					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'))
1609
					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) )
1610
					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'))
1611
					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) )
1612
					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'))
1613
					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))
1614
					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'))
1615
					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) )
1616
					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'))
1617
				WHERE
1618
					ATTR.status = 'valid'
1619
					AND EAD.status IN ( " . $ead_status . " )
1620
					AND ATTRIBUTE_GROUP.status = 'valid'
1621
					AND EAD.entity_type_id = '" . $entityId . "' " . $moreQuery . "
1622
			ORDER BY ATTRIBUTE_GROUP.position",
1623
		$elementId, $elementId, $elementId, $elementId, $elementId, $elementId);
1624
1625
		$elementsWithAttributeAndValues = $wpdb->get_results($query);
1626
1627
		return $elementsWithAttributeAndValues;
1628
	}
1629
1630
	/**
1631
	 * Check if an attribute or an attribute set section have to be displayed on the product output un frontend
1632
	 *
1633
	 * @param string $attribute_main_config The main configuration for display for the attribute
1634
	 * @param array $attribute_custom_config The custom config defined into product page
1635
	 * @param string $attribute_or_set Define if we check for an attribute or for an attribute set section
1636
	 * @param string $attribute_code The code of element to check the display for
1637
	 * @param string $output_type The current output type
1638
	 *
1639
	 * @return boolean The result to know if the element has to be displayed on frontend
1640
	 */
1641
	public static function check_attribute_display( $attribute_main_config, $attribute_custom_config, $attribute_or_set, $attribute_code, $output_type) {
1642
		if ( $attribute_main_config === 'yes' ) {
1643
			$attribute_output = true;
1644
			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' )
1645
				 || empty($attribute_custom_config) ) {
1646
				$attribute_output = true;
1647
			}
1648
			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')) )  {
1649
				$attribute_output = false;
1650
			}
1651
		}
1652
		elseif ( $attribute_main_config === 'no' ) {
1653
			$attribute_output = false;
1654
			if ( empty($attribute_custom_config[$attribute_or_set]) || empty($attribute_custom_config[$attribute_or_set][$attribute_code]) ) {
1655
				$attribute_output = false;
1656
			}
1657
			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') )  {
1658
				$attribute_output = true;
1659
			}
1660
		}
1661
1662
		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...
1663
	}
1664
1665
	/**
1666
	 * Traduit le shortcode et affiche la valeur d'un attribut donn�
1667
	 * @param array $atts : tableau de param�tre du shortcode
1668
	 * @return mixed
1669
	 **/
1670
	public static function wpshop_att_val_func($atts) {
1671
		global $wpdb;
1672
		global $wp_query;
1673
1674
		$attribute = self::getElement( $atts['attid'] );
1675
		if(empty($atts['pid'])) $atts['pid'] = $wp_query->posts[0]->ID;
1676
		$attribute_main_config = ( empty($atts['output_type']) || ($atts['output_type'] == 'complete_sheet') ) ? $attribute->is_visible_in_front : $attribute->is_visible_in_front_listing;
1677
		$output_type = ( empty($atts['output_type']) || ($atts['output_type'] == 'complete_sheet') ) ? 'complete_sheet' : 'mini_output';
1678
		$product_attribute_custom_config = get_post_meta($atts['pid'], WPSHOP_PRODUCT_FRONT_DISPLAY_CONF, true);
1679
		$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...
1680
1681
		if ( !empty( $attribute->data_type ) ) {
1682
			$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...
1683
1684
			$has_value = false;
1685
			$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'] );
1686
			if ( in_array($attribute->backend_input, array('multiple-select', 'checkbox')) ) {
1687
				$list_of_value = $wpdb->get_results($query);
1688
				if ( !empty($list_of_value) ) {
1689
					foreach ( $list_of_value as $value ) {
1690
						$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...
1691
					}
1692
					$has_value = true;
1693
				}
1694
			}
1695
			else {
1696
				$data = $wpdb->get_var($query);
1697
				if ( !empty($data) ) {
1698
					$has_value = true;
1699
				}
1700
				elseif( !empty($attribute->default_value) ) {
1701
					$has_value = true;
1702
					$data = $attribute->default_value;
1703
				}
1704
			}
1705
			$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...
1706
1707
			$attributeDefinition['data_type'] = $attribute->data_type;
1708
			$attributeDefinition['code'] = $attribute->code;
1709
			$attributeDefinition['is_requiring_unit'] = $attribute->is_requiring_unit;
1710
			$attributeDefinition['backend_input'] = $attribute->backend_input;
1711
			$attributeDefinition['data_type_to_use'] = $attribute->data_type_to_use;
1712
			$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...
1713
			$attribute_value = $attribute_display[0];
1714
			$attributeDefinition['value'] = $attribute_display[1];
1715
			$attribute_unit_list = $attribute_display[2];
1716
1717
			$result = (!empty($atts) && !empty($atts['with_label']) && ($atts['with_label'] == 'yes') ? $attribute->frontend_label . ' : ' : '') . $attribute_value . ' ' . $attribute_unit_list;
1718
1719
			return $has_value ? $result : '';
1720
		}
1721
1722
		return null;
1723
	}
1724
	/**
1725
	 * Build the output for an attribute field
1726
	 *
1727
	 * @param object $attribute The complete definition for an attribute
1728
	 * @param string $attribute_value Optionnal The current value for the attribute
1729
	 * @param array $specific_argument Optionnal The different parameters used for filter output
1730
	 * @return array The definition for the field used to display an attribute
1731
	 */
1732
	public static function get_attribute_field_definition( $attribute, $attribute_value = '', $specific_argument = array() ) {
1733
		global $wpdb;
1734
		$wpshop_price_attributes = unserialize(WPSHOP_ATTRIBUTE_PRICES);
1735
		$wpshop_weight_attributes = unserialize(WPSHOP_ATTRIBUTE_WEIGHT);
1736
		$input_def = array();
1737
		$input_def['option'] = $input_def['field_container_class'] = '';
1738
		$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 . ']');
1739
		$input_def['input_domain'] = $attributeInputDomain;
1740
		$input_def['id'] = (!empty($specific_argument) && !empty($specific_argument['field_id']) ? $specific_argument['field_id'] . '_' : '') . 'attribute_' . $attribute->id;
1741
		$input_def['intrinsec'] = $attribute->is_intrinsic;
1742
		$input_def['name'] = $attribute->code;
1743
		$input_def['type'] = wpshop_tools::defineFieldType($attribute->data_type, $attribute->frontend_input, $attribute->frontend_verification);
1744
		$input_def['label'] = $attribute->frontend_label;
1745
		$attribute_default_value = stripslashes($attribute->default_value);
1746
		$input_def['value'] = $attribute_default_value;
1747
		$input_def['default_value'] = $attribute_default_value;
1748
		$input_def['is_unique'] = $attribute->is_unique;
1749
		$input_def['_need_verification'] = $attribute->_need_verification;
1750
		$input_def['required'] = $attribute->is_required;
1751
		$input_def['frontend_verification'] = $attribute->frontend_verification;
1752
		$input_def['data_type'] = $attribute->data_type;
1753
		$input_def['data_type_to_use'] = $attribute->data_type_to_use;
1754
		$input_def['backend_type'] = $attribute->backend_input;
1755
		$input_def['frontend_type'] = $attribute->frontend_input;
1756
		$input_def['is_used_in_quick_add_form'] = $attribute->is_used_in_quick_add_form;
1757
1758
		if ( !empty($attribute_value) && !is_object($attribute_value) ) {
1759
			$input_def['value'] = $attribute_value;
1760
		}
1761
		else if ( !empty($attribute_value->value) ) {
1762
			$input_def['value'] = stripslashes($attribute_value->value);
1763
		}
1764
		else if ( !empty($specific_argument['element_identifier']) && empty($attribute_value) && (get_post_status($specific_argument['element_identifier']) != 'auto-draft') ) {
1765
			$input_def['value'] = '';
1766
		}
1767
1768
		$input_def['options'] = '';
1769
		$input_more_class = !empty($specific_argument['input_class']) ? $specific_argument['input_class'] : '';
1770
		if ($attribute->data_type == 'datetime') {
1771
			$date_config = unserialize( $attribute->default_value );
1772
			if ((($date_config['default_value'] == '') || ($date_config['default_value'] == 'date_of_current_day')) && ($date_config['default_value'] == 'date_of_current_day')) {
1773
				$input_def['value'] = date('Y-m-d');
1774
			}
1775
			else {
1776
				/**	Modification due to a message on eoxia forum: http://www.eoxia.com/forums/topic/bug-attribut-de-type-date-dans-fiche-produit-admin/	*/
1777
				$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 ) : '' );
1778
			}
1779
			$input_more_class .= ' wpshop_input_datetime ';
1780
			$field_script = '<script type="text/javascript" >
1781
	jQuery(document).ready(function(){
1782
		wpshop("#' . $input_def['id'] . '").datepicker();
1783
		wpshop("#' . $input_def['id'] . '").datepicker("option", "dateFormat", "yy-mm-dd");
1784
		wpshop("#' . $input_def['id'] . '").datepicker("option", "changeMonth", true);
1785
		wpshop("#' . $input_def['id'] . '").datepicker("option", "changeYear", true);
1786
		wpshop("#' . $input_def['id'] . '").datepicker("option", "yearRange", "-90:+10");
1787
		wpshop("#' . $input_def['id'] . '").datepicker("option", "navigationAsDateFormat", true);
1788
		wpshop("#' . $input_def['id'] . '").val("' . str_replace(" 00:00:00", "", $input_def['value']) . '");';
1789
1790
			if ( !empty($date_config['field_options']['attribute_type_date_options_available_date_past_futur']) ) {
1791 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...
1792
					$field_script .= '
1793
		wpshop("#' . $input_def['id'] . '").datepicker("option", "minDate", "' . $date_config['field_options']['attribute_type_date_options_available_date_past_futur']['minDate'][0] . '");';
1794
				}
1795 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...
1796
					$field_script .= '
1797
		wpshop("#' . $input_def['id'] . '").datepicker("option", "maxDate", "' . $date_config['field_options']['attribute_type_date_options_available_date_past_futur']['maxDate'][0] . '");';
1798
				}
1799
			}
1800
1801
			$script_options = $script_options_params = array();
1802
			if ( !empty($date_config['field_options']['attribute_type_date_options_day_to_show']) ) {
1803
				$day_to_show_list = '    ';
1804
				foreach ( $date_config['field_options']['attribute_type_date_options_day_to_show'] as $day_to_show ) {
1805
					$day_to_show_list .= '(date.getDay() == ' . $day_to_show . ') || ';
1806
				}
1807
				$script_options[] = '( ' . substr($day_to_show_list, 0, -4) . ' )';
1808
			}
1809
1810
			if ( !empty($date_config['field_options']['attribute_type_date_options_available_date_type'][0]) ) {
1811
				if ( !empty($date_config['field_options']['attribute_type_date_options_available_date']) ) {
1812
					$available_date = ' ';
1813
					foreach ( $date_config['field_options']['attribute_type_date_options_available_date'] as $avalaible_date_list ) {
1814
						if ( !empty($avalaible_date_list) ) {
1815
							$available_date .= '"' . $avalaible_date_list . '",';
1816
						}
1817
					}
1818
					$script_options_params[] = 'var dates = [' . substr($available_date, 0, -1) . ']';
1819
					$script_options[] = '(jQuery.inArray(dmy, dates) ' . ($date_config['field_options']['attribute_type_date_options_available_date_type'][0] == 'available' ? '!=' : '==') . ' -1)';
1820
				}
1821
			}
1822
1823
			if ( !empty( $script_options ) ) {
1824
				$field_script .= '
1825
		wpshop("#' . $input_def['id'] . '").datepicker("option", "beforeShowDay", function(date){
1826
			' . implode(' ', $script_options_params) . ';
1827
			var Y = date.getFullYear();
1828
			var M = (date.getMonth()+1);
1829
			if( M < 10) {
1830
				M = "0" + M;
1831
			}
1832
			var D = date.getDate();
1833
			if( D < 10) {
1834
				D = "0" + D;
1835
			}
1836
			dmy = Y + "-" + M + "-" + D;
1837
			if ( ' . implode(' && ', $script_options) . ' ) {
1838
				return [true, ""];
1839
		  	}
1840
			else {
1841
		   		return [false,""];
1842
		  	}
1843
		});';
1844
			}
1845
1846
			$field_script .= '
1847
	});
1848
</script>';
1849
			$input_def['options'] .= $field_script;
1850
		}
1851
		if ( in_array($attribute->backend_input, array('multiple-select', 'select', 'radio', 'checkbox'))) {
1852
			$input_more_class .= (!empty($specific_argument['no_chosen']) ? '' : ' chosen_select ' );
1853
			$input_def['type'] = ((!empty($specific_argument['from']) && ($specific_argument['from'] == 'frontend')) || (!is_admin() && empty($specific_argument['from'])) ? $attribute->frontend_input : $attribute->backend_input);
1854
			$input_def['valueToPut'] = 'index';
1855
1856
			$select_display = self::get_select_output($attribute, $specific_argument);
1857
			if ( empty( $input_def[ 'options_label' ] ) && !empty( $specific_argument ) && (!empty($specific_argument['from']) && ($specific_argument['from'] == 'frontend') ) ) {
1858
				$input_def[ 'options_label' ][ 'original' ] = true;
1859
			}
1860
			$input_def['options'] .= $select_display['more_input'];
1861
			$input_def['possible_value'] = (!empty($select_display) && !empty($select_display['possible_value'])) ? $select_display['possible_value'] : '';
1862
			if ( !is_admin() ) {
1863
				$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" />';
1864
			}
1865
			if ( in_array($attribute->backend_input, array('multiple-select', 'checkbox')) && is_admin() && (empty($specific_argument['from']) || ($specific_argument['from'] != 'frontend')) ) {
1866
				$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');
1867
			}
1868
		}
1869
		$input_def['label_pointer'] = 'for="' . $input_def['id'] . '"';
1870
		if(($input_def['type'] == 'radio') || ($input_def['type'] == 'checkbox')){
1871
			$input_def['label_pointer'] = '';
1872
		}
1873
1874
		/*
1875
		 * Specifc treatment for price attributes
1876
		 */
1877
		if((WPSHOP_PRODUCT_PRICE_PILOT == 'HT') && ($attribute->code == WPSHOP_PRODUCT_PRICE_TTC) ){
1878
			$input_def['option'] .= ' readonly="readonly" ';
1879
			$input_more_class .= ' wpshop_prices_readonly';
1880
		}
1881
		elseif((WPSHOP_PRODUCT_PRICE_PILOT == 'TTC') && ($attribute->code == WPSHOP_PRODUCT_PRICE_HT) ){
1882
			$input_def['option'] .= ' readonly="readonly" ';
1883
			$input_more_class .= ' wpshop_prices_readonly';
1884
		}
1885
		if ($attribute->code == WPSHOP_PRODUCT_PRICE_TAX_AMOUNT) {
1886
			$input_def['option'] .= ' readonly="readonly" ';
1887
			$input_more_class .= ' wpshop_prices_readonly';
1888
		}
1889
1890
		$input_def['label'] = str_replace("\\", "", $input_def['label']);
1891
// 		$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...
1892
		$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 : '' ) . '" ';
1893
		$input_def['title'] = !empty($attribute->frontend_help_message) ? ' title="' . $attribute->frontend_help_message . '" ' : '';
1894
1895
		if (($attribute->is_intrinsic == 'yes') && ((!empty($input_def['value'])) || ($input_def['value'] > 0))) {
1896
			$input_def['option'] .= ' readonly="readonly" ';
1897
		}
1898
1899
		/*
1900
		 * Add the unit to the attribute if attribute configuration is set to yes
1901
		 */
1902
		if ($attribute->is_requiring_unit == 'yes') {
1903
			if ( in_array($attribute->code, $wpshop_price_attributes) || ( WPSHOP_COST_OF_POSTAGE == $attribute->code) ) {
1904
				$input_def['options'] .= '&nbsp;<span class="attribute_currency" id="attribute_currency_' . $attribute->id . '" >' . wpshop_tools::wpshop_get_currency() . '</span>';
1905
			}
1906
			elseif ( in_array($attribute->code, $wpshop_weight_attributes) ) {
1907
				$weight_defaut_unity_option = get_option('wpshop_shop_default_weight_unity');
1908
				$query = $wpdb->prepare('SELECT name FROM '. WPSHOP_DBT_ATTRIBUTE_UNIT . ' WHERE id=%d', $weight_defaut_unity_option);
1909
				$unity = $wpdb->get_var( $query );
1910
				$input_def['options'] .= '&nbsp;<span class="attribute_weight" id="attribute_weight_' . $attribute->id . '" >' . __($unity, 'wpshop') . '</span>';
1911
			}
1912
			else {
1913
				unset($unit_input_def);
1914
				$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...
1915
				$unit_input_def['type'] = 'select';
1916
				$unit_input_def['option'] = ' class="wpshop_attribute_unit_input chosen_select" ';
1917
				$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;
1918
				$unit_input_def['name'] = $attribute->code;
1919
				$unit_input_def['value'] = (!empty($attribute_value->unit_id) ? $attribute_value->unit_id : '');
1920
				if($unit_input_def['value'] == ''){
1921
					if ( $attribute->_default_unit > 0 ) {
1922
						$unit_input_def['value'] = $attribute->_default_unit;
1923
					}
1924
					else {
1925
						$unit_input_def['value'] = wpshop_attributes_unit::get_default_unit_for_group($attribute->_unit_group_id);
1926
					}
1927
				}
1928
				$input_def['options'] .= wpshop_form::check_input_type($unit_input_def, $attributeInputDomain . '[unit]');
1929
			}
1930
		}
1931
1932
		/*
1933
		 * Add indication on postage cost tax
1934
		 */
1935
		if ( $attribute->code == WPSHOP_COST_OF_POSTAGE ) {
1936
			$input_def['options'] .= ' <span class="attribute_currency" >' . __('ATI', 'wpshop') . '</span>';
1937
		}
1938
1939
		/*
1940
		 * Create the field output
1941
		 */
1942
		if ( is_admin() && ($attribute->data_type == 'datetime') && ($attribute->is_user_defined == 'yes') && (empty($specific_argument['from']) || ($specific_argument['from'] != 'frontend')) ) {
1943
			$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'));
1944
			$input_def['options'] = '';
1945
			$input_def['label_pointer'] = '';
1946
			$input_def['option'] = substr( $input_def['option'], 0 , -2 ) . ' wpshop_attributes_is_user_defined_admin_field "';
1947
			$input_def['field_container_class'] .= 'wpshop_attributes_is_user_defined_admin_container';
1948
		}
1949
		else {
1950
			$input_def['output'] = wpshop_form::check_input_type($input_def, $attributeInputDomain);
1951
		}
1952
		return $input_def;
1953
	}
1954
1955
	/**
1956
	 *
1957
	 * @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...
1958
	 * @param string $output_from
1959
	 * @return string The output for
1960
	 */
1961
	public static function display_attribute( $attribute_code, $output_from = 'admin', $output_specs = array() ) {
1962
		$output = '';
1963
		/*	Get the page code	*/
1964
		$currentPageCode = !empty($output_specs['page_code']) ? $output_specs['page_code'] : '';
1965
		$element_identifier = !empty($output_specs['element_identifier']) ? $output_specs['element_identifier'] : '';
1966
1967
		/*	Get attribute definition	*/
1968
		$attribute_def = wpshop_attributes::getElement($attribute_code, "'valid'", 'code');
1969
1970
		/*	Get attribute input definition	*/
1971
		$current_value = (!empty($output_specs['current_value']) ? $output_specs['current_value'] : '');
1972
		$input = wpshop_attributes::get_attribute_field_definition( $attribute_def, $current_value, array_merge($output_specs, array('input_class' => ' wpshop_attributes_display', 'from' => $output_from)) );
1973
1974
		/*	Create default output	*/
1975
		$input_to_display = $input['output'] . $input['options'];
1976
1977
		/*	Check if current field is linked to an addon, and if the addon is activated	*/
1978
		$addons_list = unserialize(WPSHOP_ADDONS_LIST);
1979
		foreach ( $addons_list as $addon_code => $addon_def ) {
1980
			if ( in_array($attribute_code, $addon_def) ) {
1981
				if ( constant($addon_code) === false ) {
1982
					$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>';
1983
				}
1984
			}
1985
		}
1986
1987
		/*	Check the prices attribute because output for this attributes is customized	*/
1988
		$price_tab = unserialize(WPSHOP_ATTRIBUTE_PRICES);
1989
		unset($price_tab[array_search(WPSHOP_COST_OF_POSTAGE, $price_tab)]);
1990
1991
 		$output['field'] = '
1992
<div class="wpshop_cls" >
1993
	<div class="wpshop_form_label ' . $currentPageCode . '_' . $input['name'] . '_label ' . (in_array($attribute_def->code, $price_tab) ? $currentPageCode . '_prices_label ' : '') . ' alignleft" >
1994
		<label ' . $input['label_pointer'] . ' >' . __($input['label'], 'wpshop') . ($attribute_def->is_required == 'yes' ? ' <span class="wpshop_required" >*</span>' : '') . '</label>
1995
	</div>
1996
	<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" >
1997
		' . $input_to_display . '
1998
	</div>';
1999
2000
// 		$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...
2001
// 		$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>' : '');
2002
// 		$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>';
2003
2004
		/*
2005
		 * Display attribute option if applicable
2006
		 */
2007 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...
2008
			$attribute_option_display = $attribute_def->backend_input=='select' && (strtolower( __(self::get_attribute_type_select_option_info($input['value'], 'value'), 'wpshop') ) == strtolower(__('yes', 'wpshop'))) ? '' : ' wpshopHide';
2009
2010
			$output['field'] .= '
2011
	<div class="attribute_option_'.$attribute_def->code.''.$attribute_option_display.'">'.self::get_attribute_option_fields($element_identifier, $attribute_def->code).'</div>';
2012
		}
2013
2014
		$output['field'] .= '</div>';
2015
		$output['field_definition'] = $input;
2016
2017
		return $output;
2018
	}
2019
2020
	/**
2021
	 * Output the different tabs into an entity sheet
2022
	 *
2023
	 * @param string $element_code The current element type represented by the code
2024
	 * @param integer $element_id The current element identifier to dislay tabs for
2025
	 * @param array $element_definition An array with the different configuration for the current element
2026
	 *
2027
	 * @return string The html code to output directly tabs
2028
	 */
2029
	public static function attribute_of_entity_to_tab( $element_code, $element_id, $element_definition ) {
2030
		$attributeContentOutput = '';
2031
2032
		/**	Get the different attribute affected to the entity	*/
2033
		$element_atribute_list = wpshop_attributes::getElementWithAttributeAndValue($element_code, $element_id, WPSHOP_CURRENT_LOCALE, '', 'frontend');
2034
2035
2036
		if ( is_array($element_atribute_list) && (count($element_atribute_list) > 0) ) {
2037
			foreach ( $element_atribute_list[$element_id] as $attributeSetSectionName => $attributeSetContent ) {
2038
				$attributeToShowNumber = 0;
2039
				$attributeOutput = '';
2040
2041
				foreach ( $attributeSetContent['attributes'] as $attributeId => $attributeDefinition ) {
2042
2043
					/**	Check the value type to check if empty or not	*/
2044
					if ( $attributeDefinition['data_type'] == 'int' ) {
2045
						$attributeDefinition['value'] = (int)$attributeDefinition['value'];
2046
					}
2047
					else if ( $attributeDefinition['data_type'] == 'decimal' ) {
2048
						$attributeDefinition['value'] = (float)$attributeDefinition['value'];
2049
					}
2050
2051
					/** Check if the attribute is set to be displayed in frontend	*/
2052
					$attribute_display_state = wpshop_attributes::check_attribute_display( $attributeDefinition['is_visible_in_front'], $element_definition['custom_display'], 'attribute', $attributeDefinition['code'], 'complete_sheet');
2053
2054
					/**	Output the field if the value is not null	*/
2055
2056
					if ( (is_array($attributeDefinition['value']) || ( !empty($attributeDefinition['value']) ) ) && $attribute_display_state) {
2057
2058
						$attribute_display = wpshop_attributes::wps_attribute_values_display( $attributeDefinition );
2059
						$attribute_value = $attribute_display[0];
2060
						$attributeDefinition['value'] = $attribute_display[1];
2061
						$attribute_unit_list = $attribute_display[2];
2062
2063
						/** Template parameters	*/
2064
						$template_part = 'product_attribute_display';
2065
						$tpl_component = array();
2066
						$tpl_component['PDT_ENTITY_CODE'] = self::currentPageCode;
2067
						$tpl_component['ATTRIBUTE_CODE'] = $attributeDefinition['attribute_code'];
2068
						$tpl_component['ATTRIBUTE_LABEL'] = __($attributeDefinition['frontend_label'], 'wpshop');
2069
						$tpl_component['ATTRIBUTE_VALUE'] = (  !is_array($attribute_value) ) ? stripslashes($attribute_value) : $attribute_value;
2070
						$tpl_component['ATTRIBUTE_VALUE_UNIT'] =  $attribute_unit_list;
2071
2072
						/** Build template	*/
2073
						$attributeOutput .= wpshop_display::display_template_element($template_part, $tpl_component);
2074
						unset($tpl_component);
2075
2076
						$attributeToShowNumber++;
2077
					}
2078
				}
2079
2080
				/** Check if the attribute set section is set to be displayed in frontend	*/
2081
				$attribute_set_display_state = wpshop_attributes::check_attribute_display( $attributeSetContent['display_on_frontend'], $element_definition['custom_display'], 'attribute_set_section', $attributeSetContent['code'], 'complete_sheet');
2082
2083
				if ( !$attribute_set_display_state ) {
2084
					$attributeToShowNumber = 0;
2085
					$attributeOutput = '';
2086
				}
2087
				$element_atribute_list[$element_id][$attributeSetSectionName]['count'] = $attributeToShowNumber;
2088
				$element_atribute_list[$element_id][$attributeSetSectionName]['output'] = $attributeOutput;
2089
			}
2090
2091
			/** Gestion de l'affichage	*/
2092
			$tab_list = $content_list = '';
2093
			foreach ( $element_atribute_list[$element_id] as $attributeSetSectionName => $attributeSetContent ) {
2094
				if ( !empty($attributeSetContent['count']) > 0 ) {
2095
					/** Template parameters	*/
2096
					$template_part = 'product_attribute_tabs';
2097
					$tpl_component = array();
2098
					$tpl_component['ATTRIBUTE_SET_CODE'] = $attributeSetContent['code'];
2099
					$tpl_component['ATTRIBUTE_SET_NAME'] = __($attributeSetSectionName, 'wpshop');
2100
2101
					/** Build template	*/
2102
					$tpl_way_to_take = wpshop_display::check_way_for_template($template_part);
2103
					if ( $tpl_way_to_take[0] && !empty($tpl_way_to_take[1]) ) {
2104
						/*	Include the old way template part	*/
2105
						ob_start();
2106
						require(wpshop_display::get_template_file($tpl_way_to_take[1]));
2107
						$tab_list .= ob_get_contents();
2108
						ob_end_clean();
2109
					}
2110
					else {
2111
						$tab_list .= wpshop_display::display_template_element($template_part, $tpl_component);
2112
					}
2113
					unset($tpl_component);
2114
2115
					/** Template parameters	*/
2116
					$template_part = 'product_attribute_tabs_detail';
2117
					$tpl_component = array();
2118
					$tpl_component['ATTRIBUTE_SET_CODE'] = $attributeSetContent['code'];
2119
					$tpl_component['ATTRIBUTE_SET_CONTENT'] = $attributeSetContent['output'];
2120
2121
					/** Build template	*/
2122
					$tpl_way_to_take = wpshop_display::check_way_for_template($template_part);
2123
					if ( $tpl_way_to_take[0] && !empty($tpl_way_to_take[1]) ) {
2124
						/*	Include the old way template part	*/
2125
						ob_start();
2126
						require(wpshop_display::get_template_file($tpl_way_to_take[1]));
2127
						$content_list .= ob_get_contents();
2128
						ob_end_clean();
2129
					}
2130
					else {
2131
						$content_list .= wpshop_display::display_template_element($template_part, $tpl_component);
2132
					}
2133
					unset($tpl_component);
2134
				}
2135
			}
2136
2137
			if ( $tab_list != '' ) {
2138
				/** Template parameters	*/
2139
				$template_part = 'product_attribute_container';
2140
				$tpl_component = array();
2141
				$tpl_component['PDT_TABS'] = apply_filters( 'wpshop_extra_tabs_menu_before', '' ).$tab_list.apply_filters( 'wpshop_extra_tabs_menu_after', '' );
2142
				$tpl_component['PDT_TAB_DETAIL'] = apply_filters( 'wpshop_extra_tabs_content_before', '' ).$content_list.apply_filters( 'wpshop_extra_tabs_content_after', '' );
2143
2144
				/** Build template	*/
2145
				$tpl_way_to_take = wpshop_display::check_way_for_template($template_part);
2146
				if ( $tpl_way_to_take[0] && !empty($tpl_way_to_take[1]) ) {
2147
					/*	Include the old way template part	*/
2148
					ob_start();
2149
					require(wpshop_display::get_template_file($tpl_way_to_take[1]));
2150
					$attributeContentOutput = ob_get_contents();
2151
					ob_end_clean();
2152
				}
2153
				else {
2154
					$attributeContentOutput = wpshop_display::display_template_element($template_part, $tpl_component);
2155
				}
2156
				unset($tpl_component);
2157
			}
2158
		}
2159
2160
		return $attributeContentOutput;
2161
	}
2162
2163
	/**
2164
	 * Display value for a given attribute
2165
	 *
2166
	 * @param unknown_type $attributeDefinition
2167
	 * @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...
2168
	 */
2169
	public static function wps_attribute_values_display( $attributeDefinition ) {
2170
		$attribute_unit_list = '';
2171
		if ( !empty($attributeDefinition['unit']) ) {
2172
			/** Template parameters	*/
2173
			$template_part = 'product_attribute_unit';
2174
			$tpl_component = array();
2175
			$tpl_component['ATTRIBUTE_UNIT'] = $attributeDefinition['unit'];
2176
2177
			/** Build template	*/
2178
			$attribute_unit_list = wpshop_display::display_template_element($template_part, $tpl_component);
2179
			unset($tpl_component);
2180
		}
2181
2182
		$attribute_value = $attributeDefinition['value'];
2183
		if ( $attributeDefinition['data_type'] == 'decimal' ) {
2184
			$attribute_value =(is_numeric($attribute_value) ) ? number_format($attribute_value, 2, ',', '') : $attribute_value;
2185
			if ( in_array($attributeDefinition['code'], unserialize(WPSHOP_ATTRIBUTE_PRICES)) ) {
2186
				if ( $attributeDefinition['is_requiring_unit'] == 'yes' ) {
2187
					$attribute_unit_list = ' ' . wpshop_tools::wpshop_get_currency();
2188
				}
2189
				$attributeDefinition['value'] = wpshop_display::format_field_output('wpshop_product_price', $attributeDefinition['value']);
2190
			}
2191
		}
2192
		if ( $attributeDefinition['data_type'] == 'datetime' ) {
2193
			$attribute_value = mysql2date('d/m/Y', $attributeDefinition['value'], true);
2194
		}
2195
		if ( $attributeDefinition['backend_input'] == 'select' ) {
2196
			$attribute_value = wpshop_attributes::get_attribute_type_select_option_info($attributeDefinition['value'], 'label', $attributeDefinition['data_type_to_use']);
2197
		}
2198
		/** Manage differently if its an array of values or not	*/
2199
		if ( $attributeDefinition['backend_input'] == 'multiple-select') {
2200
			$attribute_value = '';
2201
			if ( is_array($attributeDefinition['value']) ) {
2202
				foreach ($attributeDefinition['value'] as $v) {
2203
					$attribute_value .= ' / '.wpshop_attributes::get_attribute_type_select_option_info($v, 'label', $attributeDefinition['data_type_to_use']);
2204
				}
2205
			}
2206
			else $attribute_value = ' / '.wpshop_attributes::get_attribute_type_select_option_info($attributeDefinition['value'], 'label', $attributeDefinition['data_type_to_use']);
2207
			$attribute_value = substr($attribute_value,3);
2208
		}
2209
2210
		return array($attribute_value, $attributeDefinition['value'], $attribute_unit_list);
2211
	}
2212
2213
	/**
2214
	 * Manage display for the output when user uses a shortcode for attributes display
2215
	 * @param array $shorcode_args The list of argument passed through the shortcode
2216
	 */
2217
	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...
2218
		$output = '';
2219
		/*
2220
		 * Read the attribute list
2221
		*/
2222
		foreach ( explode(', ', $shorcode_args['attributes']) as $attribute_code ) {
2223
			$attribute_output_def = wpshop_attributes::display_attribute( $attribute_code, $shorcode_args['from'] );
2224
			$output .= $attribute_output_def['field'];
2225
		}
2226
2227
		return $output;
2228
	}
2229
2230
	/**
2231
	 *
2232
	 * @param unknown_type $attributeSetId
2233
	 * @param unknown_type $currentPageCode
2234
	 * @param unknown_type $itemToEdit
2235
	 * @param unknown_type $outputType
2236
	 * @return Ambigous <multitype:, string>
2237
	 */
2238
	public static function entities_attribute_box($attributeSetId, $currentPageCode, $itemToEdit, $outputType = 'box') {
2239
		$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...
2240
		$box['boxMore'] = '';
2241
		/*	Get the attribute set details in order to build the product interface	*/
2242
		$productAttributeSetDetails = wpshop_attributes_set::getAttributeSetDetails($attributeSetId, "'valid','deleted'");
2243
		$attribute_specification = array('page_code' => $currentPageCode, 'element_identifier' => $itemToEdit, 'field_id' => $currentPageCode . '_' . $itemToEdit . '_');
2244
2245
		if ( count($productAttributeSetDetails) > 0 ) {
2246
			/*	Read the attribute list in order to output	*/
2247
			$shortcodes_attr = '';
2248
			$shortcodes_to_display = false;
2249
			$attribute_set_id_is_present = false;
2250
2251
			foreach ($productAttributeSetDetails as $productAttributeSetDetail) {
0 ignored issues
show
Bug introduced by
The expression $productAttributeSetDetails of type string is not traversable.
Loading history...
2252
2253
				$shortcodes = $currentTabContent = '';
2254
				$output_nb = 0;
2255
				if(count($productAttributeSetDetail['attribut']) >= 1){
2256
					foreach($productAttributeSetDetail['attribut'] as $attribute){
2257
2258
						if ( !empty($attribute->id) ) {
2259
							if ( $attribute->code == 'product_attribute_set_id' ) {
2260
								$attribute_set_id_is_present = true;
2261
							}
2262
2263
							/** Generic part for attribute field output	*/
2264
							$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));
2265
							$product_meta = get_post_meta( $itemToEdit, '_wpshop_product_metadata', true);
2266
2267
							/**	Check if value is empty and get value in meta if not empty	*/
2268
							$value = (empty($value) && !empty($product_meta[$attribute->code])) ? $product_meta[$attribute->code] : (!empty($value) ? $value : null);
2269
2270
							/*	Manage specific field as the attribute_set_id in product form	*/
2271
							if ( $attribute->code == 'product_attribute_set_id' ) {
2272
2273
								$value = empty($value) ? $attributeSetId : $value;
2274
							}
2275
							$attribute_specification['current_value'] = $value;
2276
							$attribute_output_def = apply_filters( 'wpshop_attribute_output_def', wpshop_attributes::display_attribute( $attribute->code, 'admin', $attribute_specification), $itemToEdit );
2277
							if ( ($attribute_output_def['field_definition']['type'] != 'hidden') && ($attribute->code != 'product_attribute_set_id') ) {
2278
								$currentTabContent .= $attribute_output_def['field'];
2279
								$shortcode_code_def=array();
2280
								$shortcode_code_def['attribute_'.str_replace('-', '_', sanitize_title($attribute_output_def['field_definition']['label']))]['main_code'] = 'wpshop_att_val';
2281
								$shortcode_code_def['attribute_'.str_replace('-', '_', sanitize_title($attribute_output_def['field_definition']['label']))]['attrs_exemple']['type'] = $attribute->data_type;
2282
								$shortcode_code_def['attribute_'.str_replace('-', '_', sanitize_title($attribute_output_def['field_definition']['label']))]['attrs_exemple']['attid'] = $attribute->id;
2283
								$shortcode_code_def['attribute_'.str_replace('-', '_', sanitize_title($attribute_output_def['field_definition']['label']))]['attrs_exemple']['pid'] = $itemToEdit;
2284
								ob_start();
2285
								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...
2286
								$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>';
2287
								ob_end_clean();
2288
							}
2289
							else {
2290
								if ( $attribute->code == 'product_attribute_set_id' ) {
2291
									$attribute_output_def['field_definition']['type'] = 'hidden';
2292
								}
2293
								$currentTabContent .=  wpshop_form::check_input_type($attribute_output_def['field_definition'], $attribute_output_def['field_definition']['input_domain']);
2294
							}
2295
							$output_nb++;
2296
						}
2297
					}
2298
2299
					$currentTabContent = apply_filters( 'wps_entity_attribute_edition', $currentTabContent, $itemToEdit, $productAttributeSetDetail );
2300
2301
					$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...
2302
					$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...
2303
					$shortcode_code['attributes_set']['attrs_exemple']['sid'] = $productAttributeSetDetail['id'];
2304
					ob_start();
2305
					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');
2306
					$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>';
2307
					ob_end_clean();
2308
2309
					if( WPSHOP_PRODUCT_SHORTCODE_DISPLAY_TYPE == 'each-box' )
2310
						$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>';
2311
					else
2312
						$shortcodes_attr .= $attribute_group_display;
2313
2314
					if ( $output_nb <= 0 ) {
2315
						$currentTabContent = __('Nothing avaiblable here. You can go in attribute management interface in order to add content here.', 'wpshop');
2316
					}
2317
				}
2318
2319
				if ($output_nb > 0) {
2320
					$shortcodes_to_display = true;
2321
					if ( $outputType == 'box' ) {
2322
						$box['box'][$productAttributeSetDetail['code']] = $productAttributeSetDetail['name'];
2323
						$box['box'][$productAttributeSetDetail['code'].'_backend_display_type'] = $productAttributeSetDetail['backend_display_type'];
2324
						$box['boxContent'][$productAttributeSetDetail['code']] = '
2325
			<div id="wpshop_' . $currentPageCode . '_' . wpshop_tools::slugify($productAttributeSetDetail['code'], array('noAccent')) . '_form" >' . $currentTabContent . '
2326
							</div><div class="wpshop_cls" ></div>';
2327
					}
2328
					else if ( $outputType == 'column' ) {
2329
						$currentTabContent = str_replace('wpshop_form_input_element', 'wpshop_form_input_column', $currentTabContent);
2330
						$currentTabContent = str_replace('wpshop_form_label', 'wpshop_form_label_column', $currentTabContent);
2331
2332
						$box['columnTitle'][$productAttributeSetDetail['code']] = __($productAttributeSetDetail['name'], 'wpshop');
2333
						$box['columnContent'][$productAttributeSetDetail['code']] = $currentTabContent;
2334
					}
2335
				}
2336
			}
2337
2338
			if( !$attribute_set_id_is_present ) {
2339
				/*	Get attribute definition	*/
2340
				$attribute_def = wpshop_attributes::getElement('product_attribute_set_id', "'valid'", 'code');
2341
				/*	Get attribute input definition	*/
2342
				$input = wpshop_attributes::get_attribute_field_definition( $attribute_def, $attributeSetId, array_merge($attribute_specification, array('input_class' => ' wpshop_attributes_display', 'from' => 'admin')) );
2343
				$input['type'] = 'hidden';
2344
2345
				$box['boxMore'] = wpshop_form::check_input_type($input, $input['input_domain']);
2346
			}
2347
2348
			/*	Ajout de la boite permettant d'ajouter des valeurs aux attributs de type liste deroulante a la volee	*/
2349
			$dialog_title = __('New value for attribute', 'wpshop');
2350
			$dialog_identifier = 'wpshop_new_attribute_option_value_add';
2351
			$dialog_input_identifier = 'wpshop_new_attribute_option_value';
2352
			ob_start();
2353
			include(WPSHOP_TEMPLATES_DIR.'admin/add_new_element_dialog.tpl.php');
2354
			$box['boxMore'] .= ob_get_contents();
2355
			ob_end_clean();
2356
			$box['boxMore'] .= '<input type="hidden" name="wpshop_attribute_type_select_code" value="" id="wpshop_attribute_type_select_code" />';
2357
2358
			if ( $shortcodes_to_display ) {
2359
				switch ( WPSHOP_PRODUCT_SHORTCODE_DISPLAY_TYPE ) {
2360
					case 'fixed-tab':
2361
					case 'movable-tab':
2362
						if ($outputType == 'box') {
2363
							$box['box']['shortcode'] = __('Product Shortcodes', 'wpshop');
2364
							$box['boxContent']['shortcode'] = $shortcodes_attr;
2365
							$box['box']['shortcode_backend_display_type'] = WPSHOP_PRODUCT_SHORTCODE_DISPLAY_TYPE;
2366
						}
2367
						else{
2368
							$box['columnTitle']['shortcode'] = __('Product Shortcodes', 'wpshop');
2369
							$box['columnContent']['shortcode'] = $shortcodes_attr;
2370
						}
2371
						break;
2372
				}
2373
			}
2374
		}
2375
2376
		return $box;
2377
	}
2378
2379
	/**
2380
	 * Generate the list of element to put into a combobox
2381
	 *
2382
	 * @param object $attribute Complete definition of attribute to generate output for
2383
	 * @return array The output for the combobox
2384
	 */
2385
	public static function get_select_output($attribute, $provenance = array()) {
2386
		global $wpdb;
2387
		$ouput = array();
2388
		$ouput['more_input'] = '';
2389
2390
		$attribute_default_value = $attribute->default_value;
2391 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...
2392
			$tmp_default_value = unserialize($attribute->default_value);
2393
			$attribute_default_value = !empty($tmp_default_value["default_value"]) ? $tmp_default_value["default_value"] : null;
2394
		}
2395
2396
		if ( $attribute->data_type_to_use == 'custom') {
2397
			$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);
2398
			$attribute_select_options = $wpdb->get_results($query);
2399
2400
			/*	Read existing element list for creating the possible values	*/
2401
			foreach ($attribute_select_options as $index => $option) :
2402
				$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...
2403
// 				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...
2404
//					$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 . '" />';
2405
// 				}
2406
			endforeach;
2407
		}
2408
		elseif ( $attribute->data_type_to_use == 'internal')  {
2409
			switch ($attribute_default_value) {
2410
				case 'users':
2411
					$users = get_users('orderby=nicename');
2412
					foreach($users as $user){
2413
						$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...
2414
					}
2415
				break;
2416
				default:
2417
					wp_reset_query();
2418
					$wpshop_attr_custom_post_query = new WP_Query(array(
2419
						'post_type' => $attribute_default_value,
2420
						'posts_per_page' => -1,
2421
						'post_status' => array( 'publish', 'draft', 'future' ) ,
2422
					));
2423
2424
					if($wpshop_attr_custom_post_query->have_posts()):
2425
						foreach($wpshop_attr_custom_post_query->posts as $post){
2426
							$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...
2427
						}
2428
					endif;
2429
					wp_reset_query();
2430
				break;
2431
			}
2432
		}
2433
2434
		/*	There is no value existing for this value	*/
2435
		if (empty($attribute_select_options_list)) :
2436
			$ouput['more_input'].=__('Nothing found for this field', 'wpshop');
2437
		else:
2438
			/*	Add a default value to the combobox list	*/
2439
			$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...
2440
			$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...
2441 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...
2442
				$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...
2443
				$tmp_default_value = unserialize($attribute->default_value);
2444
				$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...
2445
			}
2446
			//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...
2447
			foreach ( $attribute_select_options_list as $option_key => $option_value ) {
2448
				$ouput['possible_value'][$option_key] = stripslashes($option_value);
2449
			}
2450
		endif;
2451
2452
		/*	Add a extra element to create a new element into list	*/
2453
		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...
2454
			/**	$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.'" />';	*/
2455
		}
2456
		else if ( 'yes' == $attribute->is_used_in_quick_add_form ) {
2457
			$tpl_component = array();
2458
			$tpl_component['NEW_ELEMENT_CREATION_FIELD'] = 'attribute[new_value_creation][' . $attribute->code . ']';
2459
			$ouput['more_input'] .= wpshop_display::display_template_element('quick_entity_specific_field_new_element', $tpl_component);
2460
		}
2461
2462
		return $ouput;
2463
	}
2464
2465
	public static function get_affected_value_for_list( $attribute_code, $element_id, $attribute_data_type ) {
2466
		global $wpdb;
2467
		$affected_value = array();
2468
2469
		if ( $attribute_data_type == 'custom' ) {
2470
			$query = $wpdb->prepare("
2471
SELECT ATT_SELECT_OPTIONS_VALUE.id AS chosen_val, ATT_SELECT_OPTIONS_VALUE.value
2472
FROM " . WPSHOP_DBT_ATTRIBUTE . " AS ATT
2473
	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) )
2474
	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) )
2475
WHERE ATT.code = %s
2476
	AND ATT_SELECT_OPTIONS_VALUE.status = 'valid'
2477
GROUP BY ATT.id, chosen_val", $element_id, $attribute_code);
2478
		}
2479
		else {
2480
			$query = $wpdb->prepare("
2481
SELECT P.ID AS chosen_val, P.post_title
2482
FROM " . WPSHOP_DBT_ATTRIBUTE . " AS ATT
2483
	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) )
2484
	INNER JOIN " . $wpdb->posts . " AS P ON ( P.id = ATT_INT_VAL.value )
2485
WHERE ATT.code = %s
2486
	AND P.post_status = 'publish'
2487
GROUP BY ATT.id, chosen_val", $element_id, $attribute_code);
2488
		}
2489
2490
		$attribute_values_for_variations = $wpdb->get_results($query);
2491
		foreach ( $attribute_values_for_variations as $attribute_def ) {
2492
			$affected_value[] = (int) $attribute_def->chosen_val;
2493
		}
2494
2495
		return $affected_value;
2496
	}
2497
2498
	public static function get_attribute_option_output($item, $attr_code, $attr_option, $additionnal_params = '') {
2499
		switch($attr_code){
2500
			case 'is_downloadable_':
2501
				$option = get_post_meta($item['item_id'], 'attribute_option_'.$attr_code, true);
2502
				switch($attr_option){
2503
					case 'file_url':
2504
						if(in_array($additionnal_params['order_status'], array('completed', 'shipped')) && (!empty($item['item_'.$attr_code]) && (strtolower(__($item['item_'.$attr_code], 'wpshop')) == __('yes','wpshop'))) ){
2505
							$file_url = isset($option[$attr_option]) ? $option[$attr_option] : false;
2506
							return $file_url;
2507
						}
2508
						return false;
2509
						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...
2510
				}
2511
				break;
2512
		}
2513
	}
2514
2515
	public static function get_attribute_option_fields($postid, $code) {
2516
2517
		switch($code){
2518
			case 'is_downloadable_':
2519
				$data = get_post_meta($postid, 'attribute_option_'.$code, true);
2520
				$data['file_url'] = !empty($data['file_url'])?$data['file_url']:__('No file selected', 'wpshop');
2521
				$fields =  wp_nonce_field( 'ajax_wpshop_show_downloadable_interface_in_admin'.$postid, '_show_downloadable_interface_in_admin_wpnonce', true, false );
2522
				$fields .= '<div class="wpshop_form_label alignleft">&nbsp;</div>
2523
						<div class="wpshop_form_input_element alignleft">
2524
						<div class="send_downloadable_file_dialog wpshop_add_box" data-post="'.$postid.'" title="' .__('Send the downloadable file', 'wpshop'). '"></div>
2525
						<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>
2526
						<input type="hidden" class="product_identifer_field" value="' .( !empty($postid) ? esc_attr( $postid ) : '') . '" /><br/><u>'.__('File url','wpshop').' :</u>
2527
						<div class="is_downloadable_statut_'.$postid.'"><a href="' .$data['file_url']. '" target="_blank" download>'.basename($data['file_url']).'</a></div>
2528
						</div>';
2529
				return $fields;
2530
				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...
2531
2532
			default:
2533
				return '';
2534
				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...
2535
		}
2536
2537
	}
2538
2539
	/**
2540
	 *	Return content informations about a given attribute
2541
	 *
2542
	 *	@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)
2543
	 *	@param integer $entity_id The current entity we want to have the attribute value for
2544
	 *	@param string $entity_type The current entity type code we want to have the attribute value for
2545
	 *
2546
	 *	@return object $attribute_value_content The attribute content
2547
	 */
2548
	public static function get_attribute_value_content($attribute_code, $entity_id, $entity_type) {
2549
		$attribute_value_content = '';
2550
2551
		$atributes = self::getElement($attribute_code, "'valid'", 'code');
2552
		if ( !empty($atributes) ) {
2553
			$attribute_value_content = self::getAttributeValueForEntityInSet($atributes->data_type, $atributes->id,  wpshop_entities::get_entity_identifier_from_code($entity_type), $entity_id);
2554
		}
2555
2556
		return $attribute_value_content;
2557
	}
2558
2559
	/**
2560
	 * Define a function allowing to manage default value for datetime attributes
2561
	 *
2562
	 * @param mixed $value
2563
	 * @return string The complete interface allowing to manage datetime attribute field
2564
	 */
2565
	public static function attribute_type_date_config( $value ) {
2566
		$date_config_output = '';
2567
		$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...
2568
		$input_def['type'] = 'checkbox';
2569
		$input_def['possible_value'] = 'date_of_current_day';
2570
		$input_def['value'] = !empty($value['default_value']) ? $value['default_value'] : '';
2571
		$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>';
2572
		$date_config_output .= wpshop_form::check_input_type($input_def, WPSHOP_DBT_ATTRIBUTE);
2573
2574
		$input_def = array();
2575
		$input_def['name'] = '';
2576
		$input_def['id'] = 'wpshop_attributes_edition_table_field_attribute_type_date_options_day_to_show';
2577
		$input_def['type'] = 'checkbox';
2578
		$input_def['valueToPut'] = 'index';
2579
		$input_def['value'] = !empty($value['field_options']['attribute_type_date_options_day_to_show']) ? $value['field_options']['attribute_type_date_options_day_to_show'] : '';
2580
		$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'));
2581
		$input_def['options_label']['original'] = true;
2582
		$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>';
2583
2584
		/**	Past and futur date restriction	*/
2585
		$input_def = array();
2586
		$input_def['name'] = '';
2587
		$input_def['type'] = 'text';
2588
		$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/>';
2589
		$available_type_input_def = array();
2590
		$available_type_input_def['name'] = '';
2591
		$available_type_input_def['id'] = 'wpshop_attributes_edition_table_field_attribute_type_date_options_available_date_past_futur_minimum';
2592
		$available_type_input_def['type'] = 'text';
2593
		$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] : '';
2594
		$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/>';
2595
		$available_type_input_def = array();
2596
		$available_type_input_def['name'] = '';
2597
		$available_type_input_def['id'] = 'wpshop_attributes_edition_table_field_attribute_type_date_options_available_date_past_futur_maximum';
2598
		$available_type_input_def['type'] = 'text';
2599
		$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] : '';
2600
		$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/>';
2601
		$date_config_output .= '</div>';
2602
2603
		$input_def = array();
2604
		$input_def['name'] = '';
2605
		$input_def['type'] = 'text';
2606
		$date_config_output .= '
2607
<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>
2608
<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/>';
2609
2610
		$available_type_input_def = array();
2611
		$available_type_input_def['name'] = '';
2612
		$available_type_input_def['id'] = 'wpshop_attributes_edition_table_field_attribute_type_date_options_available_date_type';
2613
		$available_type_input_def['type'] = 'radio';
2614
		$available_type_input_def['valueToPut'] = 'index';
2615
		$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('');
2616
		$available_type_input_def['possible_value'] = array('' => __('No restriction', 'wpshop'), 'available' => __('Date below are available', 'wpshop'), 'unavailable' => __('Date below are unvailable', 'wpshop'));
2617
		$available_type_input_def['options_label']['original'] = true;
2618
		$date_config_output .= wpshop_form::check_input_type($available_type_input_def, WPSHOP_DBT_ATTRIBUTE . '_options[attribute_type_date_options_available_date_type]') . '<br/>';
2619
2620
		$existing = 0;
2621
		if ( !empty($value['field_options']['attribute_type_date_options_available_date']) ) {
2622
			foreach ( $value['field_options']['attribute_type_date_options_available_date'] as $index => $value ) {
2623
				if ( !empty($value) ) {
2624
					$input_def['value'] = $value;
2625
					$input_def['id'] = 'wpshop_attributes_edition_table_field_attribute_type_date_options_available_date_' . $index;
2626
					$date_config_output .= wpshop_form::check_input_type($input_def, WPSHOP_DBT_ATTRIBUTE . '_options[attribute_type_date_options_available_date]') . '<br/>';
2627
					$existing++;
2628
				}
2629
			}
2630
		}
2631
		$input_def['value'] = '';
2632
		$input_def['id'] = 'wpshop_attributes_edition_table_field_attribute_type_date_options_available_date';
2633
		$date_config_output .= wpshop_form::check_input_type($input_def, WPSHOP_DBT_ATTRIBUTE . '_options[attribute_type_date_options_available_date]');
2634
		$date_config_output .= '
2635
	<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" >
2636
</div>';
2637
2638
		return $date_config_output;
2639
	}
2640
2641
	/**
2642
	 * Met a jour un ou plusieurs attributes concernant un produit
2643
	 * @param integer $entityId Id du produit
2644
	 * @param array $values Valeurs d'attributs
2645
	 * @return array
2646
	 */
2647
	public static function setAttributesValuesForItem($entityId, $values=array(), $defaultValueForOthers=false, $from = 'webservice') {
2648
		$message='';
2649
		$attribute_available = array();
2650
		$attribute_final = array();
2651
		$entity_type = get_post_type($entityId);
2652
		$data = self::get_attribute_list_for_item( wpshop_entities::get_entity_identifier_from_code($entity_type), $entityId, WPSHOP_CURRENT_LOCALE);
2653
		foreach($data as $d) $attribute_available[$d->attribute_code] = array('attribute_id' => $d->attribute_id, 'data_type' => $d->data_type);
2654
2655
		// Creation d'un array "propre" et valide pour la fonction self::saveAttributeForEntity
2656
		foreach ( $values as $key => $value ) {
2657
			if ( in_array( $key, array_keys( $attribute_available ) ) ) {
2658
				$attribute_final[$attribute_available[$key]['data_type']][$key] = $value;
2659
			}
2660
			else $message .= sprintf(__('Impossible to set "%s" attribute', 'wpshop'), $key)."\n";
2661
		}
2662
2663
		// Pour les autres attributs non donné on leur affecte leur valeur par défaut
2664
		if ($defaultValueForOthers) {
2665
			$codes = array_keys($values);
2666
			foreach ($data as $d) {
2667
				if (!in_array($d->attribute_code, $codes)) {
2668
					$attribute_final[$d->data_type][$d->attribute_code] = $d->default_value;
2669
				}
2670
			}
2671
		}
2672
2673
		/*	Save the attributes values into wordpress post metadata database in order to have a backup and to make frontend search working	*/
2674
		$productMetaDatas = array();
2675
		foreach ($attribute_final as $attributeType => $attributeValues) {
2676
			foreach ($attributeValues as $attributeCode => $attributeValue) {
2677
				$productMetaDatas[$attributeCode] = $attributeValue;
2678
			}
2679
		}
2680
2681
		switch ( $entity_type ) {
2682
			case WPSHOP_NEWTYPE_IDENTIFIER_PRODUCT:
2683
					$meta_key = WPSHOP_PRODUCT_ATTRIBUTE_META_KEY;
2684
				break;
2685
			default:
2686
					$meta_key = '_' . $entity_type . '_metadata';
2687
				break;
2688
		}
2689
2690
		$current = get_post_meta($entityId, $meta_key, true);
2691
		$current = empty($current) ? array() : $current;
2692
		$productMetaDatas = array_merge($current, $productMetaDatas);
2693
		update_post_meta($entityId, $meta_key, $productMetaDatas);
2694
2695
		if (!empty($attribute_final)) {
2696
			self::saveAttributeForEntity($attribute_final, wpshop_entities::get_entity_identifier_from_code($entity_type), $entityId, WPSHOP_CURRENT_LOCALE, $from);
2697
		}
2698
2699
		return array('status' => empty($message), 'message' => $message);
2700
	}
2701
2702
	/**
2703
	 * Recupere les informations concernant une option donnees dans la liste d'un attribut de type liste deroulante
2704
	 *
2705
	 * @param integer $option_id L'identifiant de l'option dont on veut recuperer les informations
2706
	 * @param string $field optionnal Le champs correspondant a l'information que l'on souhaite recuperer
2707
	 * @return string $info L'information que l'on souhaite
2708
	 */
2709
	public static function get_attribute_type_select_option_info($option_id, $field = 'label', $attribute_data_type = 'custom', $only_value = false) {
2710
		global $wpdb;
2711
		if( ! is_numeric( $option_id ) ) {
2712
			return '';
2713
		}
2714
		$option_id = (int) $option_id;
2715
		switch ( $attribute_data_type ) {
2716
			case 'internal':
2717
				$entity_infos = get_post($option_id);
2718
				if ( !empty($entity_infos) ) {
2719
					if ( !$only_value ) {
2720
						/** Template parameters */
2721
						$template_part = 'product_attribute_value_internal';
2722
						$tpl_component = array();
2723
						$tpl_component['ATTRIBUTE_VALUE_POST_LINK'] = get_permalink($option_id);
2724
						$tpl_component['ATTRIBUTE_VALUE_POST_TITLE'] = $entity_infos->post_title;
2725
2726
						foreach ( $entity_infos as $post_definition_key => $post_definition_value ) {
2727
							$tpl_component['ATTRIBUTE_VALUE_' . strtoupper($post_definition_key)] = $entity_infos->$post_definition_key;
2728
						}
2729
2730
						/** Build template	*/
2731
						$info = wpshop_display::display_template_element($template_part, $tpl_component);
2732
						unset($tpl_component);
2733
					}
2734
					else {
2735
						$info = $entity_infos->post_title;
2736
					}
2737
				}
2738
				break;
2739
2740
			default:
2741
				if ( ! array_key_exists( $option_id, self::$select_option_info_cache ) ) {
2742
					$query = $wpdb->prepare("SELECT " . $field . " FROM ".WPSHOP_DBT_ATTRIBUTE_VALUES_OPTIONS." WHERE id=%d LIMIT 1", $option_id);
2743
					self::$select_option_info_cache[$option_id] = $wpdb->get_var($query);
2744
				}
2745
				$info = self::$select_option_info_cache[$option_id];
2746
			break;
2747
		}
2748
2749
		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...
2750
	}
2751
2752
	/**
2753
	 * Get the list of existing element for list type attribute
2754
	 *
2755
	 * @param integer $attribute_id
2756
	 * @return object A wordpress database object with the list of existing element
2757
	 */
2758
	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...
2759
		global $wpdb;
2760
		$query = $wpdb->prepare("
2761
			SELECT ATTRIBUTE_COMBO_OPTION.id, ATTRIBUTE_COMBO_OPTION.label as name, ATTRIBUTE_COMBO_OPTION.value , ATTRIBUTE_VALUE_INTEGER.value_id
2762
			, ATT.default_value, ATT.data_type_to_use, ATT.use_ajax_for_filling_field
2763
			FROM " . WPSHOP_DBT_ATTRIBUTE . " AS ATT
2764
				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'))
2765
				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))
2766
			WHERE ATT.id = %d
2767
				AND ATT.status = 'valid'
2768
			GROUP BY ATTRIBUTE_COMBO_OPTION.value
2769
			ORDER BY ATTRIBUTE_COMBO_OPTION.position", $attribute_id);
2770
		$list = $wpdb->get_results($query);
2771
2772
		return $list;
2773
	}
2774
2775
	/**
2776
	 * Recupere la liste des options pour les attributs de type liste deroulante suivant le type de donnees choisi (personnalise ou interne a wordpress)
2777
	 *
2778
	 * @param integer $attribute_id L'identifiant de l'attribut pour lequel on souhaite recuperer la liste des options
2779
	 * @param string $data_type optionnal Le type de donnees choisi pour cet attribut (custom | internal)
2780
	 * @return string Le resultat sous forme de code html pour la liste des options
2781
	 */
2782
	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...
2783
		global $wpdb;
2784
		$output = '';
2785
2786
		$attribute_select_options = self::get_select_option_list_($attribute_id);
2787
2788
		/*	Add possibily to choose datat type to use with list	*/
2789
		if(empty($attribute_id) || (!empty($attribute_select_options) && empty($attribute_select_options[0]->data_type_to_use))){
2790
			unset($input_def);$input_def=array();
2791
			$input_def['label'] = __('Type of data for list', 'wpshop');
2792
			$input_def['type'] = 'radio';
2793
			$input_def['name'] = 'data_type_to_use';
2794
			$input_def['valueToPut'] = 'index';
2795
			$input_def['possible_value'] = unserialize(WPSHOP_ATTR_SELECT_TYPE);
2796
			$input_def['option'] = 'class="wpshop_cls wpshop_attr_combo_data_type"';
2797
			$input_def['value'] = $data_type.'_data';
2798
			$input_def['options_label']['original'] = true;
2799
			$output = wpshop_form::check_input_type($input_def, WPSHOP_DBT_ATTRIBUTE);
2800
		}
2801
2802
		if(!empty($attribute_id) || !empty($data_type)){
2803
			$defaut_value = ( !empty($attribute_select_options[0]) && !empty($attribute_select_options[0]->default_value) ) ? $attribute_select_options[0]->default_value : null;
2804
			$default_is_serial = false;
2805
			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 ) ) ) {
2806
				$defaut_value = unserialize($attribute_select_options[0]->default_value);
2807
				$default_is_serial = true;
2808
			}
2809
			/**	Add a custom text first item of list	*/
2810
			$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>';
2811
2812
			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'))){
2813
				$sub_output = '';
2814
				if ( !empty($attribute_select_options) && !empty($attribute_select_options[0]) && !empty($attribute_select_options[0]->id) ) {
2815
					$sub_output .= '
2816
					<li class="wpshop_attribute_combo_options_container ui-state-disabled" >
2817
						<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>
2818
					</li>';
2819
					foreach ($attribute_select_options as $options) {
2820
						$tpl_component = array();
2821
						$tpl_component['ADMIN_ATTRIBUTE_VALUES_OPTION_ID'] = $options->id;
2822
						$tpl_component['ADMIN_ATTRIBUTE_VALUES_OPTION_NAME'] = $options->name;
2823
						$tpl_component['ADMIN_ATTRIBUTE_VALUES_OPTION_DEFAULT_VALUE'] = $options->default_value;
2824
						$tpl_component['ADMIN_ATTRIBUTE_VALUES_OPTION_VALUE'] = str_replace(".", ",", $options->value);
2825
						$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"' : '');
2826
						$tpl_component['ADMIN_ATTRIBUTE_VALUE_OPTIN_ACTIONS'] = '';
2827 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...
2828
							$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');
2829
						endif;
2830
						$sub_output .= wpshop_display::display_template_element('wpshop_admin_attr_option_value_item', $tpl_component, array('type' => WPSHOP_DBT_ATTRIBUTE, 'id' => $attribute_id), 'admin');
2831
						unset($tpl_component);
2832
					}
2833
				}
2834
				$add_button = $add_dialog_box = $user_more_script = '';
2835 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...
2836
2837
					$dialog_title = __('New value for attribute', 'wpshop');
2838
					$dialog_identifier = 'wpshop_new_attribute_option_value_add';
2839
					$dialog_input_identifier = 'wpshop_new_attribute_option_value';
2840
					ob_start();
2841
					include(WPSHOP_TEMPLATES_DIR.'admin/add_new_element_dialog.tpl.php');
2842
					$add_dialog_box = ob_get_contents();
2843
					ob_end_clean();
2844
2845
					$add_button_text = __('Add a value for this attribute', 'wpshop');
2846
					$add_button_parent_class = 'wpshop_attribute_option_value_add';
2847
					$add_button_name = 'wpshop_add_option_to_select';
2848
					ob_start();
2849
					include(WPSHOP_TEMPLATES_DIR.'admin/add_new_element_with_dialog.tpl.php');
2850
					$add_button = ob_get_contents();
2851
					ob_end_clean();
2852
2853
					$user_more_script = '
2854
			jQuery("#'.$dialog_identifier.'").dialog({
2855
				modal: true,
2856
				dialogClass: "wpshop_uidialog_box",
2857
				autoOpen:false,
2858
				show: "blind",
2859
				resizable: false,
2860
				buttons:{
2861
					"'.__('Add', 'wpshop').'": function(){
2862
						var data = {
2863
							action: "new_option_for_select",
2864
							wpshop_ajax_nonce: "' . wp_create_nonce("wpshop_new_option_for_attribute_creation") . '",
2865
							attribute_new_label: jQuery("#'.$dialog_input_identifier.'").val(),
2866
							attribute_identifier: "' . $attribute_id . '"
2867
						};
2868
						jQuery.post(ajaxurl, data, function(response) {
2869
							if( response[0] ) {
2870
								jQuery("#sortable_attribute li:last-child").before(response[1]);
2871
								jQuery("#wpshop_new_attribute_option_value_add").dialog("close");
2872
							}
2873
							else {
2874
								alert(response[1]);
2875
							}
2876
							jQuery("#wpshop_new_attribute_option_value_add").children("img").hide();
2877
						}, "json");
2878
2879
						jQuery(this).children("img").show();
2880
					},
2881
					"'.__('Cancel', 'wpshop').'": function(){
2882
						jQuery(this).dialog("close");
2883
					}
2884
				},
2885
				close:function(){
2886
					jQuery("#'.$dialog_input_identifier.'").val("");
2887
				}
2888
			});
2889
			jQuery(".'.$add_button_parent_class.' input").click(function(){
2890
				jQuery("#'.$dialog_identifier.'").dialog("open");
2891
			});';
2892
2893
				}
2894
				$output .= $add_dialog_box . '
2895
	<ul id="sortable_attribute" class="wpshop_cls" >'.(count($attribute_select_options)>5 ? $add_button : '').$sub_output.$add_button.'
2896
	</ul>
2897
	<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" />
2898
	<script type="text/javascript" >
2899
		wpshop(document).ready(function() {
2900
			jQuery("#sortable_attribute").sortable({
2901
				revert: true,
2902
				items: "li:not(.ui-state-disabled)"
2903
			});
2904
			' . $user_more_script . '
2905
			jQuery(".wpshop_attr_combo_data_type").live("click", function(){
2906
				if(jQuery(this).is(":checked")){
2907
					jQuery(".wpshop_attributes_edition_table_field_input_default_value").html(jQuery("#wpshopLoadingPicture").html());
2908
					var data = {
2909
						action: "attribute_output_type",
2910
						current_type: jQuery("#wpshop_attributes_edition_table_field_id_frontend_input").val(),
2911
						elementIdentifier: "'.$attribute_id.'",
2912
						data_type_to_use: jQuery(this).val(),
2913
						wpshop_ajax_nonce: "' . wp_create_nonce("wpshop_attribute_output_type_selection") . '"
2914
					};
2915
					jQuery.post(ajaxurl, data, function(response) {
2916
						jQuery(".wpshop_attributes_edition_table_field_input_default_value").html(response[0]);
2917
						jQuery(".wpshop_attributes_edition_table_field_label_default_value label").html(response[1]);
2918
						jQuery("#wpshop_attributes_edition_table_field_id_frontend_input").html();
2919
					}, "json");
2920
				}
2921
			});
2922
2923
		});
2924
	</script>';
2925
			}
2926
			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'))){
2927
				$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...
2928
				$wp_types = unserialize(WPSHOP_INTERNAL_TYPES);
2929
				unset($input_def);$input_def=array();
2930
				$input_def['label'] = __('Type of data for list', 'wpshop');
2931
				$input_def['type'] = 'select';
2932
				$input_def['name'] = 'default_value][default_value';
2933
				$input_def['id'] = 'default_value';
2934
				$input_def['valueToPut'] = 'index';
2935
				$input_def['possible_value'] = $wp_types;
2936
				$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));
2937
				$combo_wp_type = wpshop_form::check_input_type($input_def, WPSHOP_DBT_ATTRIBUTE);
2938
				$output .= '<div class="wpshop_cls">'.$combo_wp_type.'</div>';
2939
				if ( !empty($attribute_id) ) {
2940
					$option_list = '<div>' . __('You can reorder element for display them in the order you want into frontend part', 'wpshop') . '</div>';
2941
					$options_for_current_attribute = query_posts( array('post_type' => $input_def['value'], 'posts_per_page' => -1, 'orderby' => 'menu_order', 'order' => 'ASC' ) );
2942
					if ( !empty($options_for_current_attribute) ) {
2943
						$option_list .= '<ul class="wpshop_attribute_combo_values_list_container" >';
2944
						$current_order = ' ';
2945
						foreach ( $options_for_current_attribute as $options_def ) {
2946
							$current_order .= 'post_' . $options_def->ID . ',';
2947
							$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>';
2948
						}
2949
						$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" />';
2950
					}
2951
					$output .= '<div class="wpshop_cls">'.$option_list.'</div>';
2952
				}
2953
			}
2954
		}
2955
2956
		return $output;
2957
	}
2958
2959
	/**
2960
	 * Get the attribute list affected to an entity in order to generate a shortcode
2961
	 *
2962
	 * @param integer $entity_id The entity identifier for retrieving attribute list
2963
	 * @param string $list_for The type of shortcode we want to generate
2964
	 * @param string $current_post_type The post type of current edited element
2965
	 *
2966
	 * @return string The html output
2967
	 */
2968
	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...
2969
		global $wpdb;
2970
		$output = '';
2971
2972
		/*	If no entity is specified, take product as default entity	*/
2973
		$entity_id = empty($entity_id) ? wpshop_entities::get_entity_identifier_from_code(WPSHOP_NEWTYPE_IDENTIFIER_PRODUCT) : $entity_id;
2974
2975
		/*	Get attribute list for the selected enttiy	*/
2976
		$attribute_list_for_entity = self::getElement($entity_id, "'valid'", 'entity_id', true);
2977
2978
		/*	Read the list	*/
2979
		if ( !empty ($attribute_list_for_entity ) ) {
2980
			foreach ( $attribute_list_for_entity as $attribute) {
2981
				switch ($list_for) {
2982
					case 'attribute_value':
2983
							$checkbox_state = ' ';
2984
							$attribute_possible_values = '
2985
							<div class="wpshop_shortcode_element_attribute_value_product_list wpshop_shortcode_element_attribute_value_product_list_' . $attribute->id . '_container hidden" >
2986
								<select id="wpshop_shortcode_element_attribute_value_product_list_' . $attribute->id . '" class="wpshop_shortcode_element_attribute_value_product_list" >';
2987
2988
							global $post;
2989
							$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...
2990
							foreach( $posts as $post ) :
0 ignored issues
show
Bug introduced by
The expression $posts of type null is not traversable.
Loading history...
2991
								setup_postdata($post);
2992
								$attribute_possible_values .= '<option value="' . get_the_ID() . '" >' . get_the_ID() . ' - ' . get_the_title() . '</option>';
2993
							endforeach;
2994
2995
							$attribute_possible_values .= '
2996
								</select>
2997
							</div>';
2998
						break;
2999
3000
					default:
3001
						$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);
3002
						$attribute_values = $wpdb->get_results($query);
3003
3004
						$checkbox_state = 'disabled ';
3005
						$attribute_possible_values = '';
3006
						if ( !empty($attribute_values) ) {
3007
							$checkbox_state = '';
3008
							$attribute_possible_values = '
3009
							<div class="wpshop_shortcode_element_product_listing_per_attribute_value wpshop_shortcode_element_prodcut_listing_per_attribute_value_' . $attribute->code . '_container" >
3010
								<select id="wpshop_attribute_value_for_shortcode_generation_' . $attribute->id . '" class="wpshop_shortcode_element_prodcut_listing_per_attribute_value hidden" >';
3011
3012
								if ( ($attribute->data_type == 'integer') && ( ($attribute->backend_input == 'select') || ($attribute->backend_input == 'multiple-select') ) ) {
3013
									$query = $wpdb->prepare("SELECT * FROM " . WPSHOP_DBT_ATTRIBUTE_VALUES_OPTIONS . " WHERE attribute_id=%d ORDER BY position", $attribute->id);
3014
									$possible_values = $wpdb->get_results($query);
3015
									$already_selected_values = array();
3016
									foreach ($attribute_values as $attribute_value) {
3017
										if ( !empty($attribute_value->value) ) {
3018
											$already_selected_values[] = $attribute_value->value;
3019
										}
3020
									}
3021
									foreach ($possible_values as $value) {
3022
										if ( in_array( $value->id, $already_selected_values ) ) {
3023
											$attribute_possible_values .= '
3024
									<option value="' . $value->value . '" >' . $value->label . '</option>';
3025
										}
3026
									}
3027
								}
3028
								else {
3029
									foreach ($attribute_values as $attribute_value) {
3030
										if ( !empty($attribute_value->value) ) {
3031
											$attribute_possible_values .= '
3032
									<option value="' . $attribute_value->value . '" >' . $attribute_value->value . '</option>';
3033
										}
3034
									}
3035
								}
3036
								$attribute_possible_values .= '
3037
								</select>
3038
							</div>';
3039
						}
3040
						break;
3041
				}
3042
				$output .= '
3043
				<li class="wpshop_shortcode_element_container wpshop_shortcode_element_container_attributes" >
3044
					<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 . '
3045
				</li>';
3046
			}
3047
		}
3048
3049
		return $output;
3050
	}
3051
3052
	/**
3053
	 * Retrieve the attribute list into an attribute set section from a given attribute code
3054
	 *
3055
	 * @param string $attribute_code The attribute code that allows to define the attribute set section to get attribute list for
3056
	 *
3057
	 * @return object The attribute list as a wordpress database object
3058
	 */
3059
	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...
3060
		global $wpdb;
3061
3062
		$attribute_def = wpshop_attributes::getElement($attribute_code, "'valid'", 'code');
3063
3064
		/** Get the entire list of attribute in price set section for display	*/
3065
		$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);
3066
		$attribute_attribution_def = $wpdb->get_row($query);
3067
3068
		$query = $wpdb->prepare( "
3069
							SELECT ATTR.code, is_visible_in_front_listing, is_visible_in_front
3070
							FROM " . WPSHOP_DBT_ATTRIBUTE_DETAILS . " AS SET_SECTION_DETAIL
3071
								INNER JOIN " . WPSHOP_DBT_ATTRIBUTE . " AS ATTR ON (ATTR.id = SET_SECTION_DETAIL.attribute_id)
3072
							WHERE entity_type_id = %d
3073
								AND attribute_set_id = %d
3074
								AND attribute_group_id = %d",
3075
				$attribute_attribution_def->entity_type_id, $attribute_attribution_def->attribute_set_id, $attribute_attribution_def->attribute_group_id );
3076
		$atribute_list = $wpdb->get_results($query);
3077
3078
		return $atribute_list;
3079
	}
3080
3081
	/**
3082
	 * Get all attribute available for current
3083
	 * @param unknown_type $current_entity_id
3084
	 * @return Ambigous <multitype:, multitype:NULL >
3085
	 */
3086
	public static function get_variation_available_attribute( $current_entity_id ) {
3087
		global $wpdb;
3088
		$final_list = array();
3089
3090
		/**	Get all attributes defined as usable into product variation for the product type and group	*/
3091
		$query = $wpdb->prepare(
3092
				"SELECT ATT.*, ENTITY_META.meta_value
3093
				FROM " . self::getDbTable() . " AS ATT
3094
					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'))
3095
					INNER JOIN " . $wpdb->postmeta . " AS ENTITY_META ON ((ENTITY_META.meta_key = %s) AND (ENTITY_META.meta_value = ATT_DETAILS.attribute_set_id))
3096
				WHERE ATT.status IN ('valid')
3097
					AND ATT.is_used_for_variation = %s
3098
					AND ENTITY_META.post_id = %d
3099
				GROUP BY ATT_DETAILS.position, ENTITY_META.post_id, ATT.code
3100
				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
3101
		);
3102
		$attribute_list = $wpdb->get_results($query);
3103
		foreach ($attribute_list as $attribute) {
3104
			if ( !in_array($attribute->code, unserialize(WPSHOP_VARIATION_ATTRIBUTE_TO_HIDE)) && in_array($attribute->backend_input, array('select', 'multiple-select')) ) {
3105
				$attribute_values_for_variations = wpshop_attributes::get_affected_value_for_list( $attribute->code, $current_entity_id, $attribute->data_type_to_use );
3106
3107
				if ( empty($attribute_values_for_variations) ) {
3108
					$final_list['unavailable'][$attribute->code]['label'] = $attribute->frontend_label;
3109
					$final_list['unavailable'][$attribute->code]['values'] = array();
3110
					$final_list['unavailable'][$attribute->code]['attribute_complete_def'] = $attribute;
3111
				}
3112
				else {
3113
					$final_list['available'][$attribute->code]['label'] = $attribute->frontend_label;
3114
					$final_list['available'][$attribute->code]['values'] = $attribute_values_for_variations;
3115
					$final_list['available'][$attribute->code]['attribute_complete_def'] = $attribute;
3116
				}
3117
			}
3118
		}
3119
		return $final_list;
3120
	}
3121
3122
	/**
3123
	 *
3124
	 * @param integer $current_entity_id The current element edited
3125
	 * @return Ambigous <string, string, mixed>
3126
	 */
3127
	public static function get_variation_available_attribute_display( $current_entity_id, $variation_type = 'multiple' ) {
3128
		$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...
3129
3130
		$attribute_defined_as_available_for_variation = '';
3131
		if ( !empty($attribute_list) ) {
3132
			foreach ($attribute_list as $list_type => $attribute_list_by_type) {
3133
				$sub_attribute_list = '';
3134
				foreach ($attribute_list_by_type as $attribute_code => $attribute_def) {
3135
					$tpl_component = array();
3136
					if ( $list_type == 'available' ) {
3137
						$tpl_component['ADMIN_VARIATIONS_DEF_ATTRIBUTE_LABEL_STATE'] = '';
3138
						$tpl_component['ADMIN_VARIATIONS_DEF_LIST_ATTRIBUTE_CHECKBOX_STATE'] = '';
3139
						$tpl_component['ADMIN_VARIATIONS_DEF_ATTRIBUTE_TO_USE_LABEL_EXPLAINATION'] = '';
3140
					}
3141
					else {
3142
						$tpl_component['ADMIN_VARIATIONS_DEF_ATTRIBUTE_LABEL_STATE'] = ' class="wpshop_unavailable_label_variation_definition" ';
3143
						$tpl_component['ADMIN_VARIATIONS_DEF_LIST_ATTRIBUTE_CHECKBOX_STATE'] = ' disabled="disabled"';
3144
						$tpl_component['ADMIN_VARIATIONS_DEF_ATTRIBUTE_TO_USE_LABEL_EXPLAINATION'] = '';
3145
					}
3146
3147
					$tpl_component['ADMIN_ATTRIBUTE_CODE_FOR_VARIATION'] = $attribute_code;
3148
					$tpl_component['ADMIN_VARIATIONS_DEF_ATTRIBUTE_TO_USE_NAME'] = $attribute_code;
3149
					$tpl_component['ADMIN_VARIATION_ATTRIBUTE_CONTAINER_CLASS'] = ' wpshop_attribute_for_variation_' . $attribute_code;
3150
					$tpl_component['ADMIN_VARIATION_NEW_SINGLE_LABEL'] = __( $attribute_def['label'], 'wpshop' );
3151
					$tpl_component['ADMIN_VARIATION_NEW_SINGLE_INPUT'] = '';
3152
					if ( $variation_type == 'single' ) {
3153
						$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') );
3154
						if ( !empty($attribute_output_def['possible_value']) ) {
3155
							foreach( $attribute_output_def['possible_value'] as $value_id => $value ){
3156
								if ( !in_array($value_id, $attribute_def['values']) ) {
3157
									unset($attribute_output_def['possible_value'][$value_id]);
3158
								}
3159
							}
3160
						}
3161
						$tpl_component['ADMIN_VARIATION_NEW_SINGLE_INPUT'] = wpshop_form::check_input_type($attribute_output_def, $attribute_output_def['input_domain']);
3162
					}
3163
					$sub_attribute_list .= wpshop_display::display_template_element('wpshop_admin_variation_attribute_line', $tpl_component, array(), 'admin');
3164
					unset($tpl_component);
3165
				}
3166
3167
				$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');
3168
			}
3169
		}
3170
3171
		return array($attribute_defined_as_available_for_variation, ( (!empty($attribute_list['available']) ) ? $attribute_list['available'] : ''), ( ( !empty($attribute_list['unavailable']) ) ? $attribute_list['unavailable'] : ''));
3172
	}
3173
3174
	/**
3175
	 * Get attribute defined as product option specific attribute
3176
	 *
3177
	 * @param array $variations_attribute_parameters Allows to give some parameters for customize list
3178
	 * @return string The output for all specific attribute in each product with option
3179
	 */
3180
	public static function get_variation_attribute( $variations_attribute_parameters ) {
3181
		$output = '';
3182
3183
		$attribute_list = wpshop_attributes::getElement('yes', "'valid'", "is_used_in_variation", true);
3184
		if ( !empty( $attribute_list ) ) {
3185
			$tpl_component = array();
3186
			$tpl_component['ADMIN_VARIATION_DETAIL'] = '';
3187
			$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...
3188
			foreach ( $attribute_list as $attribute_def ) {
3189
3190
				$variations_attribute_parameters['field_custom_name_prefix'] = $variations_attribute_parameters['field_name'] . '[attribute][' . $attribute_def->data_type . ']';
3191
				$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 );
3192
3193
				$field_output = $attribute_output_def['output'];
3194
3195
				/*	Build array for output complete customization	*/
3196
				$tpl_component['ADMIN_VARIATION_DETAIL_LABEL_' . strtoupper($attribute_def->code)] = $attribute_output_def['label'];
3197
				$tpl_component['ADMIN_VARIATION_DETAIL_INPUT_' . strtoupper($attribute_def->code)] = $field_output;
3198
				$sub_tpl_component = array();
3199
				$sub_tpl_component['ADMIN_VARIATION_DETAIL_DEF_CODE'] = ' wpshop_variation_special_value_container_' . $attribute_output_def['name'];
3200
				$sub_tpl_component['ADMIN_VARIATION_DETAIL_DEF_ID'] = $attribute_output_def['id'];
3201
				$sub_tpl_component['ADMIN_VARIATION_DETAIL_DEF_LABEL'] = $attribute_output_def['label'];
3202
				$sub_tpl_component['ADMIN_VARIATION_DETAIL_DEF_INPUT'] = $field_output;
3203 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...
3204
					$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';
3205
					$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>';
3206
				}
3207
				$tpl_component['ADMIN_VARIATION_DETAIL'] .= wpshop_display::display_template_element('wpshop_admin_variation_item_details_line', $sub_tpl_component, array(), 'admin');
3208
				unset($sub_tpl_component);
3209
			}
3210
			$output .= wpshop_display::display_template_element('wpshop_admin_variation_item_details', $tpl_component, array(), 'admin');
3211
		}
3212
3213
		return $output;
3214
	}
3215
3216
	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...
3217
		global $wpdb;
3218
		$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...
3219
3220
		$query = $wpdb->prepare(
3221
				"SELECT ATT.*, ENTITY.post_name as entity
3222
				FROM " . self::getDbTable() . " AS ATT
3223
					INNER JOIN " . $wpdb->posts . " AS ENTITY ON (ENTITY.ID = ATT.entity_id)
3224
					INNER JOIN " . $wpdb->postmeta . " AS ENTITY_META ON ((ENTITY_META.post_id = ENTITY_ID))
3225
				WHERE ATT.status IN ('valid')
3226
					AND ATT.is_user_defined = %s
3227
					AND ATT.is_used_for_variation = %s
3228
					AND ENTITY.post_name = %s
3229
				GROUP BY ATT.id", 'yes', 'no', $use_defined_parameters['entity_type_id']
3230
		);
3231
		$attribute_user_defined_list = $wpdb->get_results($query);
3232
3233
		return $attribute_user_defined_list;
3234
	}
3235
3236
	/**
3237
	 * Define the different field available for bulk edition for entities. Attributes to display are defined by checking box in attribute option
3238
	 *
3239
	 * @param string $column_name The column name for output type definition
3240
	 * @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...
3241
	 *
3242
	 */
3243
	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...
3244
		switch ( $entity ) {
3245
			case WPSHOP_NEWTYPE_IDENTIFIER_PRODUCT:
3246
				$attribute_def = wpshop_attributes::getElement($column_name, "'valid'", 'code');
3247
				if ( !empty($attribute_def) ) {
3248
					$input_def = self::get_attribute_field_definition( $attribute_def, '', array('input_class' => ' wpshop_bulk_and_quick_edit_input') );
3249
					$input = wpshop_form::check_input_type($input_def, $input_def['input_domain']);
3250
?>
3251
	<div class="wpshop_bulk_and_quick_edit_column_container wpshop_bulk_and_quick_edit_column_<?php echo $column_name; ?>_container">
3252
		<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>
3253
		<?php echo str_replace('chosen_select', '', str_replace('alignleft', '', $input)); ?>
3254
	</div>
3255
<?php
3256
			}
3257
			break;
3258
		}
3259
	}
3260
3261
	/**
3262
	 * Define the different field available for bulk edition for entities. Attributes to display are defined by checking box in attribute option
3263
	 *
3264
	 * @param string $column_name The column name for output type definition
3265
	 * @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...
3266
	 *
3267
	 */
3268
	public static function bulk_edit( $column_name, $entity ) {
3269
		switch ( $entity ) {
3270
			case WPSHOP_NEWTYPE_IDENTIFIER_PRODUCT:
3271
				$attribute_def = wpshop_attributes::getElement($column_name, "'valid'", 'code');
3272
				if ( !empty($attribute_def) ) {
3273
					$input_def = self::get_attribute_field_definition( $attribute_def, '', array('input_class' => ' wpshop_bulk_and_quick_edit_input') );
3274
					$input = wpshop_form::check_input_type($input_def, $input_def['input_domain']);
3275
?>
3276
	<div class="wpshop_bulk_and_quick_edit_column_container wpshop_bulk_and_quick_edit_column_<?php echo $column_name; ?>_container">
3277
		<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>
3278
		<?php echo str_replace('chosen_select', '', str_replace('alignleft', '', $input)); ?>
3279
		<!-- <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="" />  -->
3280
	</div>
3281
<?php
3282
			}
3283
			break;
3284
		}
3285
	}
3286
3287
}
3288
3289
?>
3290