Issues (4138)

classes/integrations/woocommerce/class-account.php (7 issues)

1
<?php
2
namespace lsx_health_plan\classes\integrations\woocommerce;
3
4
/**
5
 * Contains the downloads functions post type
6
 *
7
 * @package lsx-health-plan
8
 */
9
class Account {
10
11
	/**
12
	 * Holds class instance
13
	 *
14
	 * @since 1.0.0
15
	 *
16
	 * @var      object \lsx_health_plan\classes\integrations\woocommerce\Account()
17
	 */
18
	protected static $instance = null;
19
20
	/**
21
	 * Constructor
22
	 */
23
	public function __construct() {
24
		add_action( 'init', array( $this, 'init' ), 20, 1 );
25
26
		// Redirect to the Edit Account Template.
27
		add_filter( 'template_include', array( $this, 'account_endpoint_redirect' ), 99 );
28
29
		add_action( 'woocommerce_edit_account_form', array( $this, 'print_user_frontend_fields' ), 10 );
30
31
		add_filter( 'lsx_hp_profile_fields', array( $this, 'add_post_data_to_account_fields' ), 10, 1 );
32
		add_action( 'show_user_profile', array( $this, 'print_user_admin_fields' ), 30 );
33
34
		add_action( 'personal_options_update', array( $this, 'save_account_fields' ) );
35
		add_action( 'edit_user_profile_update', array( $this, 'save_account_fields' ) );
36
37
		add_action( 'woocommerce_save_account_details', array( $this, 'save_account_fields' ) );
38
		add_filter( 'woocommerce_save_account_details_errors', array( $this, 'validate_user_frontend_fields' ), 10 );
39
40
		// Profile Fields.
41
		add_filter( 'woocommerce_form_field_text', array( $this, 'lsx_profile_photo_field_filter' ), 10, 4 );
42
		add_action( 'woocommerce_after_edit_account_form', array( $this, 'action_woocommerce_after_edit_account_form' ), 10, 0 );
43
	}
44
45
	/**
46
	 * Return an instance of this class.
47
	 *
48
	 * @since 1.0.0
49
	 *
50
	 * @return    object \lsx_health_plan\classes\integration\woocommerce\Account()    A single instance of this class.
51
	 */
52
	public static function get_instance() {
53
		// If the single instance hasn't been set, set it now.
54
		if ( null === self::$instance ) {
55
			self::$instance = new self();
56
		}
57
		return self::$instance;
58
	}
59
60
	/**
61
	 * Runs on init
62
	 *
63
	 * @return void
64
	 */
65
	public function init() {
66
		remove_action( 'woocommerce_account_navigation', 'woocommerce_account_navigation' );
67
	}
68
69
	/**
70
	 * Redirects to the my account template.
71
	 *
72
	 * @param string $template
73
	 * @return string
74
	 */
75
	public function account_endpoint_redirect( $template ) {
76
		if ( function_exists( 'is_account_page' ) && is_account_page() ) {
77
			if ( empty( locate_template( array( 'page-template-my-plan.php' ) ) ) && file_exists( LSX_HEALTH_PLAN_PATH . 'templates/page-template-my-plan.php' ) ) {
78
				$template = LSX_HEALTH_PLAN_PATH . 'templates/page-template-my-plan.php';
79
			}
80
		}
81
		return $template;
82
	}
83
84
	/**
85
	 * Add post values to account fields if set.
86
	 *
87
	 * @param array $fields
88
	 *
89
	 * @return array
90
	 */
91
	public function add_post_data_to_account_fields( $fields ) {
92
		if ( empty( $_POST ) && wp_verify_nonce( sanitize_key( $_POST ) ) ) {
93
			return $fields;
94
		}
95
96
		foreach ( $fields as $key => $field_args ) {
97
			if ( isset( $_POST[ $key ] ) && empty( $_POST[ $key ] ) && wp_verify_nonce( sanitize_key( $_POST[ $key ] ) ) ) {
98
				$fields[ $key ]['value'] = '';
99
				continue;
100
			}
101
102
			if ( isset( $_POST[ $key ] ) ) {
103
				$fields[ $key ]['value'] = sanitize_key( $_POST[ $key ] );
104
			}
105
		}
106
107
		return $fields;
108
	}
109
110
	/**
111
	 * Add fields to registration form and account area.
112
	 */
113
	public function print_user_frontend_fields() {
114
		$fields            = $this->get_account_fields();
115
		$is_user_logged_in = is_user_logged_in();
116
117
		$all_disabled = \lsx_health_plan\functions\get_option( 'disable_all_stats', false );
118
		if ( 'on' !== $all_disabled ) {
119
			echo wp_kses_post( '<h2 class="title-lined my-stats-title">' . __( 'My Stats', 'lsx-health-plan' ) . '</h2><p><strong>' . __( 'My physical info', 'lsx-health-plan' ) . '</strong></p>' );
120
			echo wp_kses_post( '<div class="my-stats-wrap"><div class="my-stats">' );
121
			foreach ( $fields as $key => $field_args ) {
122
				$value = null;
123
				if ( ! $this->is_field_visible( $field_args ) ) {
124
					continue;
125
				}
126
				if ( $is_user_logged_in ) {
127
					$user_id = $this->get_edit_user_id();
128
					$value   = $this->get_userdata( $user_id, $key );
129
				}
130
				$value = ( isset( $field_args['value'] ) && '' !== $field_args['value'] ) ? $field_args['value'] : $value;
131
				woocommerce_form_field( $key, $field_args, $value );
0 ignored issues
show
The function woocommerce_form_field was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

131
				/** @scrutinizer ignore-call */ 
132
    woocommerce_form_field( $key, $field_args, $value );
Loading history...
132
			}
133
			$is_bmi_disabled = \lsx_health_plan\functions\get_option( 'disable_bmi_checkbox', false );
134
			if ( 'on' !== $is_bmi_disabled ) {
135
				echo wp_kses_post( '<p class="form-row calculate-bmi"><label>BMI</label><button class="btn border-btn">' . __( 'Calculate', 'lsx-health-plan' ) . '<i class="fa fa-calculator" aria-hidden="true"></i></button></p>' );
136
				echo wp_kses_post( '</div>' );
137
				echo wp_kses_post( '<div class="description"><p class="bmi-title"><strong>' . __( 'Your BMI score', 'lsx-health-plan' ) . '</strong></p>' );
138
				echo wp_kses_post( '<p>' . __( "BMI is a measurement of a person's leanness or corpulence based on their height and weight, and is intended to quantify tissue mass. It is widely used as a general indicator of whether a person has a healthy body weight for their height.", 'lsx-health-plan' ) . '</p></div></div>' );
139
			}
140
			
141
		}
142
	}
143
144
	/**
145
	 * Get user data.
146
	 *
147
	 * @param $user_id
148
	 * @param $key
149
	 *
150
	 * @return mixed|string
151
	 */
152
	public function get_userdata( $user_id, $key ) {
153
		if ( ! $this->is_userdata( $key ) ) {
154
			return get_user_meta( $user_id, $key, true );
155
		}
156
157
		$userdata = get_userdata( $user_id );
158
159
		if ( ! $userdata || ! isset( $userdata->{$key} ) ) {
160
			return '';
161
		}
162
163
		return $userdata->{$key};
164
	}
165
166
	/**
167
	 * Get currently editing user ID (frontend account/edit profile/edit other user).
168
	 *
169
	 * @return int
170
	 */
171
	public function get_edit_user_id() {
172
		return ( isset( $_GET['user_id'] ) && wp_verify_nonce( sanitize_key( $_GET['user_id'] ) ) ) ? (int) $_GET['user_id'] : get_current_user_id();
173
	}
174
175
176
	/**
177
	 * Save registration fields.
178
	 *
179
	 * @param int $customer_id
180
	 */
181
	public function save_account_fields( $customer_id ) {
182
		$nonce_value = wc_get_var( $_REQUEST['save-account-details-nonce'], wc_get_var( $_REQUEST['_wpnonce'], '' ) ); // @codingStandardsIgnoreLine.
0 ignored issues
show
The function wc_get_var was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

182
		$nonce_value = /** @scrutinizer ignore-call */ wc_get_var( $_REQUEST['save-account-details-nonce'], wc_get_var( $_REQUEST['_wpnonce'], '' ) ); // @codingStandardsIgnoreLine.
Loading history...
183
		if ( ! wp_verify_nonce( $nonce_value, 'save_account_details' ) ) {
184
			return;
185
		}
186
187
		$fields         = $this->get_account_fields();
188
		$sanitized_data = array();
189
		foreach ( $fields as $key => $field_args ) {
190
			if ( ! $this->is_field_visible( $field_args ) ) {
191
				continue;
192
			}
193
194
			$sanitize = isset( $field_args['sanitize'] ) ? $field_args['sanitize'] : 'wc_clean';
195
			$value    = ( isset( $_POST[ $key ] ) ) ? call_user_func( $sanitize, $_POST[ $key ] ) : '';
196
			if ( $this->is_userdata( $key ) ) {
197
198
				$sanitized_data[ $key ] = $value;
199
				continue;
200
			}
201
202
			if ( 'profile_photo' === $key ) {
203
				// This handles the image uploads.
204
				require_once ABSPATH . 'wp-admin/includes/image.php';
205
				require_once ABSPATH . 'wp-admin/includes/file.php';
206
				require_once ABSPATH . 'wp-admin/includes/media.php';
207
208
				$id = media_handle_upload( $key, 0, '' );
0 ignored issues
show
'' of type string is incompatible with the type array expected by parameter $post_data of media_handle_upload(). ( Ignorable by Annotation )

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

208
				$id = media_handle_upload( $key, 0, /** @scrutinizer ignore-type */ '' );
Loading history...
209
				if ( ! is_wp_error( $id ) ) {
210
					update_term_meta( $customer_id, $key . '_id', $id );
211
					update_term_meta( $customer_id, $key, $id );
212
				}
213
			} else {
214
				delete_user_meta( $customer_id, $key );
215
				update_user_meta( $customer_id, $key, $value );
216
			}
217
		}
218
219
		if ( ! empty( $sanitized_data ) ) {
220
			$sanitized_data['ID'] = $customer_id;
221
			wp_update_user( $sanitized_data );
222
		}
223
	}
224
225
226
	/**
227
	 * Is this field core user data.
228
	 *
229
	 * @param $key
230
	 *
231
	 * @return bool
232
	 */
233
	public function is_userdata( $key ) {
234
		$userdata = array(
235
			'user_pass',
236
			'user_login',
237
			'user_nicename',
238
			'user_url',
239
			'user_email',
240
			'display_name',
241
			'nickname',
242
			'first_name',
243
			'last_name',
244
			'description',
245
			'rich_editing',
246
			'user_registered',
247
			'role',
248
			'jabber',
249
			'aim',
250
			'yim',
251
			'show_admin_bar_front',
252
		);
253
254
		return in_array( $key, $userdata, true );
255
	}
256
257
	/**
258
	 * Is field visible.
259
	 *
260
	 * @param $field_args
261
	 *
262
	 * @return bool
263
	 */
264
	public function is_field_visible( $field_args ) {
265
		$visible = true;
266
		$action  = filter_input( INPUT_POST, 'action' );
267
268
		if ( is_admin() && ! empty( $field_args['hide_in_admin'] ) ) {
269
			$visible = false;
270
		} elseif ( ( is_account_page() || 'save_account_details' === $action ) && is_user_logged_in() && ! empty( $field_args['hide_in_account'] ) ) {
0 ignored issues
show
The function is_account_page was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

270
		} elseif ( ( /** @scrutinizer ignore-call */ is_account_page() || 'save_account_details' === $action ) && is_user_logged_in() && ! empty( $field_args['hide_in_account'] ) ) {
Loading history...
271
			$visible = false;
272
		} elseif ( ( is_account_page() || 'save_account_details' === $action ) && ! is_user_logged_in() && ! empty( $field_args['hide_in_registration'] ) ) {
273
			$visible = false;
274
		} elseif ( is_checkout() && ! empty( $field_args['hide_in_checkout'] ) ) {
0 ignored issues
show
The function is_checkout was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

274
		} elseif ( /** @scrutinizer ignore-call */ is_checkout() && ! empty( $field_args['hide_in_checkout'] ) ) {
Loading history...
275
			$visible = false;
276
		}
277
278
		// Disable the fitness fields if needed.
279
		$weight_key  = __( 'Weight:' );
280
		$waist_key   = __( 'Waist:' );
281
		$fitness_key = __( 'BMI Score:' );
282
		if ( $weight_key === $field_args['label'] || $waist_key === $field_args['label'] || $fitness_key === $field_args['label'] ) {
283
284
			// Check if all stats are disabled.
285
			$all_disabled = \lsx_health_plan\functions\get_option( 'disable_all_stats', false );
286
287
			$option_key = '';
288
			switch ( $field_args['label'] ) {
289
				case $weight_key:
290
					$option_key = 'disable_weight_checkbox';
291
					break;
292
293
				case $weight_key:
294
					$option_key = 'disable_height_checkbox';
295
					break;
296
				
297
				case $waist_key:
298
					$option_key = 'disable_waist_checkbox';
299
					break;
300
301
				case $fitness_key:
302
					$option_key = 'disable_bmi_checkbox';
303
					break;
304
			}
305
			$is_disabled = \lsx_health_plan\functions\get_option( $option_key, false );
306
			if ( 'on' === $all_disabled || 'on' === $is_disabled ) {
307
				$visible = false;
308
			}
309
		}
310
		return $visible;
311
	}
312
313
	/**
314
	 * Add fields to admin area.
315
	 */
316
	public function print_user_admin_fields() {
317
		$fields = $this->get_account_fields();
318
		?>
319
		<h2><?php esc_html_e( 'Additional Information', 'lsx-health-plan' ); ?></h2>
320
		<table class="form-table" id="iconic-additional-information">
321
			<tbody>
322
			<?php foreach ( $fields as $key => $field_args ) { ?>
323
				<?php
324
				if ( ! $this->is_field_visible( $field_args ) ) {
325
					continue;
326
				}
327
328
				$user_id = $this->get_edit_user_id();
329
				$value   = get_user_meta( $user_id, $key, true );
330
				?>
331
				<tr>
332
					<th>
333
						<label for="<?php echo esc_html( $key ); ?>"><?php echo esc_html( $field_args['label'] ); ?></label>
334
					</th>
335
					<td>
336
						<?php $field_args['label'] = false; ?>
337
						<?php woocommerce_form_field( $key, $field_args, $value ); ?>
0 ignored issues
show
The function woocommerce_form_field was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

337
						<?php /** @scrutinizer ignore-call */ woocommerce_form_field( $key, $field_args, $value ); ?>
Loading history...
338
					</td>
339
				</tr>
340
			<?php } ?>
341
			</tbody>
342
		</table>
343
		<?php
344
	}
345
346
	/**
347
	 * Validate fields on frontend.
348
	 *
349
	 * @param WP_Error $errors
0 ignored issues
show
The type lsx_health_plan\classes\...ns\woocommerce\WP_Error was not found. Did you mean WP_Error? If so, make sure to prefix the type with \.
Loading history...
350
	 *
351
	 * @return WP_Error
352
	 */
353
	public function validate_user_frontend_fields( $errors ) {
354
		$fields = $this->get_account_fields();
355
356
		foreach ( $fields as $key => $field_args ) {
357
			if ( empty( $field_args['required'] ) ) {
358
				continue;
359
			}
360
361
			/*if ( ! isset( $_POST['register'] ) && wp_verify_nonce( sanitize_key( $_POST['register'] ) ) && ! empty( $field_args['hide_in_account'] ) ) {
362
				continue;
363
			}*/
364
365
			if ( isset( $_POST['register'] ) && wp_verify_nonce( sanitize_key( $_POST['register'] ) ) && ! empty( $field_args['hide_in_registration'] ) ) {
366
				continue;
367
			}
368
369
			if ( empty( $_POST[ $key ] ) ) {
370
				/* translators: %s: field */
371
				$message = sprintf( __( '%s is a required field.', 'lsx-health-plan' ), '<strong>' . $field_args['label'] . '</strong>' );
372
				$errors->add( $key, $message );
373
			}
374
		}
375
376
		return $errors;
377
	}
378
379
	/**
380
	 * Changes the text into a file upload.
381
	 * @param $field
382
	 * @param $key
383
	 * @param $args
384
	 * @param $value
385
	 *
386
	 * @return mixed
387
	 */
388
	public function lsx_profile_photo_field_filter( $field, $key, $args, $value ) {
389
		if ( 'profile_photo' === $args['id'] ) {
390
391
			if ( $args['required'] ) {
392
				$args['class'][] = 'validate-required';
393
				$required        = ' <abbr class="required" title="' . esc_attr__( 'required', 'lsx-health-plan' ) . '">*</abbr>';
394
			} else {
395
				$required = '';
396
			}
397
398
			if ( is_string( $args['label_class'] ) ) {
399
				$args['label_class'] = array( $args['label_class'] );
400
			}
401
402
			if ( is_null( $value ) ) {
403
				$value = $args['default'];
404
			}
405
406
			// Custom attribute handling.
407
			$custom_attributes         = array();
408
			$args['custom_attributes'] = array_filter( (array) $args['custom_attributes'], 'strlen' );
409
410
			if ( $args['maxlength'] ) {
411
				$args['custom_attributes']['maxlength'] = absint( $args['maxlength'] );
412
			}
413
414
			if ( ! empty( $args['autocomplete'] ) ) {
415
				$args['custom_attributes']['autocomplete'] = $args['autocomplete'];
416
			}
417
418
			if ( true === $args['autofocus'] ) {
419
				$args['custom_attributes']['autofocus'] = 'autofocus';
420
			}
421
422
			if ( ! empty( $args['custom_attributes'] ) && is_array( $args['custom_attributes'] ) ) {
423
				foreach ( $args['custom_attributes'] as $attribute => $attribute_value ) {
424
					$custom_attributes[] = esc_attr( $attribute ) . '="' . esc_attr( $attribute_value ) . '"';
425
				}
426
			}
427
428
			if ( ! empty( $args['validate'] ) ) {
429
				foreach ( $args['validate'] as $validate ) {
430
					$args['class'][] = 'validate-' . $validate;
431
				}
432
			}
433
434
			$field_html      = '';
435
			$field           = '';
436
			$label_id        = $args['id'];
437
			$sort            = $args['priority'] ? $args['priority'] : '';
438
			$field_container = '<p class="form-row %1$s" id="%2$s" data-priority="' . esc_attr( $sort ) . '">%3$s</p>';
439
			$args['class'][] = 'validate-required';
440
			$required        = ' <abbr class="required" title="' . esc_attr__( 'required', 'lsx-health-plan' ) . '">*</abbr>';
441
442
			$field .= '<input accept="image/*" type="file" class="input-text ' . esc_attr( implode( ' ', $args['input_class'] ) ) . '" name="' . esc_attr( $key ) . '" id="' . esc_attr( $args['id'] ) . '" placeholder="' . esc_attr( $args['placeholder'] ) . '"  value="" ' . implode( ' ', $custom_attributes ) . ' />';
443
444
			if ( '' !== $value && $value !== $args['default'] ) {
445
				$field .= '<input type="text" class="input-text ' . esc_attr( implode( ' ', $args['input_class'] ) ) . '" name="' . esc_attr( $key ) . '_id" id="' . esc_attr( $args['id'] ) . '_id" placeholder="' . esc_attr( $args['placeholder'] ) . '_id"  value="' . esc_attr( $value ) . '" ' . implode( ' ', $custom_attributes ) . ' />';
446
			}
447
448
			$field .= '<input type="hidden" name="MAX_FILE_SIZE" value="500000" />';
449
450
			if ( $args['label'] && 'checkbox' !== $args['type'] ) {
451
				$field_html .= '<label for="' . esc_attr( $label_id ) . '" class="' . esc_attr( implode( ' ', $args['label_class'] ) ) . '">' . $args['label'] . $required . '</label>';
452
			}
453
454
			$field_html .= $field;
455
456
			if ( $args['description'] ) {
457
				$field_html .= '<span class="description">' . esc_html( $args['description'] ) . '</span>';
458
			}
459
460
			$container_class = esc_attr( implode( ' ', $args['class'] ) );
461
			$container_id    = esc_attr( $args['id'] ) . '_field';
462
			$field           = sprintf( $field_container, $container_class, $container_id, $field_html );
463
		}
464
		return $field;
465
	}
466
467
468
	public function action_woocommerce_after_edit_account_form() {
469
		echo do_shortcode( '[avatar_upload /]' );
470
	}
471
472
	/**
473
	 * Get additional account fields.
474
	 *
475
	 * @return array
476
	 */
477
	public function get_account_fields() {
478
		$account_fields = apply_filters( 'lsx_hp_profile_fields', array(
479
			'age'  => array(
480
				'type'                 => 'text',
481
				'label'                => __( 'Age:', 'lsx-health-plan' ),
482
				'placeholder'          => __( '#', 'lsx-health-plan' ),
483
				'hide_in_account'      => false,
484
				'hide_in_admin'        => false,
485
				'hide_in_checkout'     => false,
486
				'hide_in_registration' => false,
487
				'required'             => false,
488
			),
489
			'weight'  => array(
490
				'type'                 => 'text',
491
				'label'                => __( 'Weight:', 'lsx-health-plan' ),
492
				'placeholder'          => __( 'kg', 'lsx-health-plan' ),
493
				'hide_in_account'      => false,
494
				'hide_in_admin'        => false,
495
				'hide_in_checkout'     => false,
496
				'hide_in_registration' => false,
497
				'required'             => false,
498
			),
499
			'gender'   => array(
500
				'type'                 => 'select',
501
				'label'                => __( 'Gender:', 'lsx-health-plan' ),
502
				'placeholder'          => __( 'm/f', 'lsx-health-plan' ),
503
				'hide_in_account'      => false,
504
				'hide_in_admin'        => false,
505
				'hide_in_checkout'     => false,
506
				'hide_in_registration' => false,
507
				'required'             => false,
508
				'options'     => array(
509
					'male'   => __( 'Male', 'lsx-health-plan' ),
510
					'female' => __( 'Female', 'lsx-health-plan' ),
511
				),
512
			),
513
			'waist'   => array(
514
				'type'                 => 'text',
515
				'label'                => __( 'Waist:', 'lsx-health-plan' ),
516
				'placeholder'          => __( 'cm', 'lsx-health-plan' ),
517
				'hide_in_account'      => false,
518
				'hide_in_admin'        => false,
519
				'hide_in_checkout'     => false,
520
				'hide_in_registration' => false,
521
				'required'             => false,
522
			),
523
			'height'     => array(
524
				'type'                 => 'text',
525
				'label'                => __( 'Height:', 'lsx-health-plan' ),
526
				'placeholder'          => __( 'cm', 'lsx-health-plan' ),
527
				'hide_in_account'      => false,
528
				'hide_in_admin'        => false,
529
				'hide_in_checkout'     => false,
530
				'hide_in_registration' => false,
531
				'required'             => false,
532
			),
533
		) );
534
535
		$is_weight_disabled = \lsx_health_plan\functions\get_option( 'disable_weight_checkbox', false );
536
		if ( 'on' === $is_weight_disabled ) {
537
			$account_fields['weight']['required'] = false;
538
		}
539
		$is_height_disabled = \lsx_health_plan\functions\get_option( 'disable_height_checkbox', false );
540
		if ( 'on' === $is_height_disabled ) {
541
			$account_fields['height']['required'] = false;
542
		}
543
		$is_waist_disabled = \lsx_health_plan\functions\get_option( 'disable_waist_checkbox', false );
544
		if ( 'on' === $is_waist_disabled ) {
545
			$account_fields['waist']['required'] = false;
546
		}
547
		return $account_fields;
548
	}
549
}
550