class-wc-customer-data-store.php 17.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
<?php
/**
 * Class WC_Customer_Data_Store file.
 *
 * @package WooCommerce\DataStores
 */

use Automattic\WooCommerce\Internal\DataStores\Orders\CustomOrdersTableController;
use Automattic\WooCommerce\Internal\DataStores\Orders\OrdersTableDataStore;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * WC Customer Data Store.
 *
 * @version  3.0.0
 */
class WC_Customer_Data_Store extends WC_Data_Store_WP implements WC_Customer_Data_Store_Interface, WC_Object_Data_Store_Interface {

	/**
	 * Data stored in meta keys, but not considered "meta".
	 *
	 * @since 3.0.0
	 * @var array
	 */
	protected $internal_meta_keys = array(
		'locale',
		'billing_postcode',
		'billing_city',
		'billing_address_1',
		'billing_address_2',
		'billing_state',
		'billing_country',
		'shipping_postcode',
		'shipping_city',
		'shipping_address_1',
		'shipping_address_2',
		'shipping_state',
		'shipping_country',
		'paying_customer',
		'last_update',
		'first_name',
		'last_name',
		'display_name',
		'show_admin_bar_front',
		'use_ssl',
		'admin_color',
		'rich_editing',
		'comment_shortcuts',
		'dismissed_wp_pointers',
		'show_welcome_panel',
		'session_tokens',
		'nickname',
		'description',
		'billing_first_name',
		'billing_last_name',
		'billing_company',
		'billing_phone',
		'billing_email',
		'shipping_first_name',
		'shipping_last_name',
		'shipping_company',
		'shipping_phone',
		'wptests_capabilities',
		'wptests_user_level',
		'syntax_highlighting',
		'_order_count',
		'_money_spent',
		'_last_order',
		'_woocommerce_tracks_anon_id',
	);

	/**
	 * Internal meta type used to store user data.
	 *
	 * @var string
	 */
	protected $meta_type = 'user';

	/**
	 * Callback to remove unwanted meta data.
	 *
	 * @param object $meta Meta object.
	 * @return bool
	 */
	protected function exclude_internal_meta_keys( $meta ) {
		global $wpdb;

		$table_prefix = $wpdb->prefix ? $wpdb->prefix : 'wp_';

		return ! in_array( $meta->meta_key, $this->internal_meta_keys, true )
			&& 0 !== strpos( $meta->meta_key, '_woocommerce_persistent_cart' )
			&& 0 !== strpos( $meta->meta_key, 'closedpostboxes_' )
			&& 0 !== strpos( $meta->meta_key, 'metaboxhidden_' )
			&& 0 !== strpos( $meta->meta_key, 'manageedit-' )
			&& ! strstr( $meta->meta_key, $table_prefix )
			&& 0 !== stripos( $meta->meta_key, 'wp_' );
	}

	/**
	 * Method to create a new customer in the database.
	 *
	 * @since 3.0.0
	 *
	 * @param WC_Customer $customer Customer object.
	 *
	 * @throws WC_Data_Exception If unable to create new customer.
	 */
	public function create( &$customer ) {
		$id = wc_create_new_customer( $customer->get_email(), $customer->get_username(), $customer->get_password() );

		if ( is_wp_error( $id ) ) {
			throw new WC_Data_Exception( $id->get_error_code(), $id->get_error_message() );
		}

		$customer->set_id( $id );
		$this->update_user_meta( $customer );

		// Prevent wp_update_user calls in the same request and customer trigger the 'Notice of Password Changed' email.
		$customer->set_password( '' );

		wp_update_user(
			apply_filters(
				'woocommerce_update_customer_args',
				array(
					'ID'           => $customer->get_id(),
					'role'         => $customer->get_role(),
					'display_name' => $customer->get_display_name(),
				),
				$customer
			)
		);
		$wp_user = new WP_User( $customer->get_id() );
		$customer->set_date_created( $wp_user->user_registered );
		$customer->set_date_modified( get_user_meta( $customer->get_id(), 'last_update', true ) );
		$customer->save_meta_data();
		$customer->apply_changes();
		do_action( 'woocommerce_new_customer', $customer->get_id(), $customer );
	}

	/**
	 * Method to read a customer object.
	 *
	 * @since 3.0.0
	 * @param WC_Customer $customer Customer object.
	 * @throws Exception If invalid customer.
	 */
	public function read( &$customer ) {
		$user_object = $customer->get_id() ? get_user_by( 'id', $customer->get_id() ) : false;

		// User object is required.
		if ( ! $user_object || empty( $user_object->ID ) ) {
			throw new Exception( __( 'Invalid customer.', 'woocommerce' ) );
		}

		$customer_id = $customer->get_id();

		// Load meta but exclude deprecated props and parent keys.
		$user_meta = array_diff_key(
			array_change_key_case( array_map( 'wc_flatten_meta_callback', get_user_meta( $customer_id ) ) ),
			array_flip( array( 'country', 'state', 'postcode', 'city', 'address', 'address_2', 'default', 'location' ) ),
			array_change_key_case( (array) $user_object->data )
		);

		$customer->set_props( $user_meta );
		$customer->set_props(
			array(
				'is_paying_customer' => get_user_meta( $customer_id, 'paying_customer', true ),
				'email'              => $user_object->user_email,
				'username'           => $user_object->user_login,
				'display_name'       => $user_object->display_name,
				'date_created'       => $user_object->user_registered, // Mysql string in local format.
				'date_modified'      => get_user_meta( $customer_id, 'last_update', true ),
				'role'               => ! empty( $user_object->roles[0] ) ? $user_object->roles[0] : 'customer',
			)
		);
		$customer->read_meta_data();
		$customer->set_object_read( true );
		do_action( 'woocommerce_customer_loaded', $customer );
	}

	/**
	 * Updates a customer in the database.
	 *
	 * @since 3.0.0
	 * @param WC_Customer $customer Customer object.
	 */
	public function update( &$customer ) {
		wp_update_user(
			apply_filters(
				'woocommerce_update_customer_args',
				array(
					'ID'           => $customer->get_id(),
					'user_email'   => $customer->get_email(),
					'display_name' => $customer->get_display_name(),
				),
				$customer
			)
		);

		// Only update password if a new one was set with set_password.
		if ( $customer->get_password() ) {
			wp_update_user(
				array(
					'ID'        => $customer->get_id(),
					'user_pass' => $customer->get_password(),
				)
			);
			$customer->set_password( '' );
		}

		$this->update_user_meta( $customer );
		$customer->set_date_modified( get_user_meta( $customer->get_id(), 'last_update', true ) );
		$customer->save_meta_data();
		$customer->apply_changes();
		do_action( 'woocommerce_update_customer', $customer->get_id(), $customer );
	}

	/**
	 * Deletes a customer from the database.
	 *
	 * @since 3.0.0
	 * @param WC_Customer $customer Customer object.
	 * @param array       $args Array of args to pass to the delete method.
	 */
	public function delete( &$customer, $args = array() ) {
		if ( ! $customer->get_id() ) {
			return;
		}

		$args = wp_parse_args(
			$args,
			array(
				'reassign' => 0,
			)
		);

		$id = $customer->get_id();
		wp_delete_user( $id, $args['reassign'] );

		do_action( 'woocommerce_delete_customer', $id );
	}

	/**
	 * Helper method that updates all the meta for a customer. Used for update & create.
	 *
	 * @since 3.0.0
	 * @param WC_Customer $customer Customer object.
	 */
	private function update_user_meta( $customer ) {
		$updated_props = array();
		$changed_props = $customer->get_changes();

		$meta_key_to_props = array(
			'paying_customer' => 'is_paying_customer',
			'first_name'      => 'first_name',
			'last_name'       => 'last_name',
		);

		foreach ( $meta_key_to_props as $meta_key => $prop ) {
			if ( ! array_key_exists( $prop, $changed_props ) ) {
				continue;
			}

			if ( update_user_meta( $customer->get_id(), $meta_key, $customer->{"get_$prop"}( 'edit' ) ) ) {
				$updated_props[] = $prop;
			}
		}

		$billing_address_props = array(
			'billing_first_name' => 'billing_first_name',
			'billing_last_name'  => 'billing_last_name',
			'billing_company'    => 'billing_company',
			'billing_address_1'  => 'billing_address_1',
			'billing_address_2'  => 'billing_address_2',
			'billing_city'       => 'billing_city',
			'billing_state'      => 'billing_state',
			'billing_postcode'   => 'billing_postcode',
			'billing_country'    => 'billing_country',
			'billing_email'      => 'billing_email',
			'billing_phone'      => 'billing_phone',
		);

		foreach ( $billing_address_props as $meta_key => $prop ) {
			$prop_key = substr( $prop, 8 );

			if ( ! isset( $changed_props['billing'] ) || ! array_key_exists( $prop_key, $changed_props['billing'] ) ) {
				continue;
			}

			if ( update_user_meta( $customer->get_id(), $meta_key, $customer->{"get_$prop"}( 'edit' ) ) ) {
				$updated_props[] = $prop;
			}
		}

		$shipping_address_props = array(
			'shipping_first_name' => 'shipping_first_name',
			'shipping_last_name'  => 'shipping_last_name',
			'shipping_company'    => 'shipping_company',
			'shipping_address_1'  => 'shipping_address_1',
			'shipping_address_2'  => 'shipping_address_2',
			'shipping_city'       => 'shipping_city',
			'shipping_state'      => 'shipping_state',
			'shipping_postcode'   => 'shipping_postcode',
			'shipping_country'    => 'shipping_country',
			'shipping_phone'      => 'shipping_phone',
		);

		foreach ( $shipping_address_props as $meta_key => $prop ) {
			$prop_key = substr( $prop, 9 );

			if ( ! isset( $changed_props['shipping'] ) || ! array_key_exists( $prop_key, $changed_props['shipping'] ) ) {
				continue;
			}

			if ( update_user_meta( $customer->get_id(), $meta_key, $customer->{"get_$prop"}( 'edit' ) ) ) {
				$updated_props[] = $prop;
			}
		}

		do_action( 'woocommerce_customer_object_updated_props', $customer, $updated_props );
	}

	/**
	 * Check if the usage of the custom orders table is enabled.
	 *
	 * @return bool
	 */
	private function is_cot_in_use(): bool {
		return wc_get_container()->get( CustomOrdersTableController::class )->custom_orders_table_usage_is_enabled();
	}

	/**
	 * Gets the customers last order.
	 *
	 * @since 3.0.0
	 * @param WC_Customer $customer Customer object.
	 * @return WC_Order|false
	 */
	public function get_last_order( &$customer ) {
		//phpcs:disable WooCommerce.Commenting.CommentHooks.MissingSinceComment
		/**
		 * Filters the id of the last order from a given customer.
		 *
		 * @param string @last_order_id The last order id as retrieved from the database.
		 * @param WC_Customer The customer whose last order id is being retrieved.
		 * @return string The actual last order id to use.
		 */
		$last_order_id = apply_filters(
			'woocommerce_customer_get_last_order',
			get_user_meta( $customer->get_id(), '_last_order', true ),
			$customer
		);
		//phpcs:enable WooCommerce.Commenting.CommentHooks.MissingSinceComment

		if ( '' === $last_order_id ) {
			global $wpdb;

			$order_statuses_sql = "( '" . implode( "','", array_map( 'esc_sql', array_keys( wc_get_order_statuses() ) ) ) . "' )";

			//phpcs:disable WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			if ( $this->is_cot_in_use() ) {
				$sql           = $wpdb->prepare(
					'SELECT id FROM ' . OrdersTableDataStore::get_orders_table_name() . "
					WHERE customer_id = %d
					AND status in $order_statuses_sql
					ORDER BY id DESC
					LIMIT 1",
					$customer->get_id()
				);
				$last_order_id = $wpdb->get_var( $sql );
			} else {
				$last_order_id = $wpdb->get_var(
					"SELECT posts.ID
				FROM $wpdb->posts AS posts
				LEFT JOIN {$wpdb->postmeta} AS meta on posts.ID = meta.post_id
				WHERE meta.meta_key = '_customer_user'
				AND   meta.meta_value = '" . esc_sql( $customer->get_id() ) . "'
				AND   posts.post_type = 'shop_order'
				AND   posts.post_status IN $order_statuses_sql
				ORDER BY posts.ID DESC
				LIMIT 1"
				);
			}
			//phpcs:enable WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			update_user_meta( $customer->get_id(), '_last_order', $last_order_id );
		}

		if ( ! $last_order_id ) {
			return false;
		}

		return wc_get_order( absint( $last_order_id ) );
	}

	/**
	 * Return the number of orders this customer has.
	 *
	 * @since 3.0.0
	 * @param WC_Customer $customer Customer object.
	 * @return integer
	 */
	public function get_order_count( &$customer ) {
		$count = apply_filters(
			'woocommerce_customer_get_order_count',
			get_user_meta( $customer->get_id(), '_order_count', true ),
			$customer
		);

		$order_statuses_sql = "( '" . implode( "','", array_map( 'esc_sql', array_keys( wc_get_order_statuses() ) ) ) . "' )";

		if ( '' === $count ) {
			global $wpdb;

			//phpcs:disable WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			if ( $this->is_cot_in_use() ) {
				$sql   = $wpdb->prepare(
					'SELECT COUNT(id) FROM ' . OrdersTableDataStore::get_orders_table_name() . "
					WHERE customer_id = %d
					AND status in $order_statuses_sql",
					$customer->get_id()
				);
				$count = $wpdb->get_var( $sql );
			} else {
				$count = $wpdb->get_var(
					"SELECT COUNT(*)
				FROM $wpdb->posts as posts
				LEFT JOIN {$wpdb->postmeta} AS meta ON posts.ID = meta.post_id
				WHERE   meta.meta_key = '_customer_user'
				AND     posts.post_type = 'shop_order'
				AND     posts.post_status IN $order_statuses_sql
				AND     meta_value = '" . esc_sql( $customer->get_id() ) . "'"
				);
			}
			//phpcs:enable WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared

			update_user_meta( $customer->get_id(), '_order_count', $count );
		}

		return absint( $count );
	}

	/**
	 * Return how much money this customer has spent.
	 *
	 * @since 3.0.0
	 * @param WC_Customer $customer Customer object.
	 * @return float
	 */
	public function get_total_spent( &$customer ) {
		$spent = apply_filters(
			'woocommerce_customer_get_total_spent',
			get_user_meta( $customer->get_id(), '_money_spent', true ),
			$customer
		);

		if ( '' === $spent ) {
			global $wpdb;

			$statuses     = array_map( 'esc_sql', wc_get_is_paid_statuses() );
			$statuses_sql = "( 'wc-" . implode( "','wc-", $statuses ) . "' )";

			//phpcs:disable WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			if ( $this->is_cot_in_use() ) {
				$sql = $wpdb->prepare(
					'SELECT SUM(total_amount) FROM ' . OrdersTableDataStore::get_orders_table_name() . "
					WHERE customer_id = %d
					AND status in $statuses_sql",
					$customer->get_id()
				);
			} else {
				$sql = "SELECT SUM(meta2.meta_value)
					FROM $wpdb->posts as posts
					LEFT JOIN {$wpdb->postmeta} AS meta ON posts.ID = meta.post_id
					LEFT JOIN {$wpdb->postmeta} AS meta2 ON posts.ID = meta2.post_id
					WHERE   meta.meta_key       = '_customer_user'
					AND     meta.meta_value     = '" . esc_sql( $customer->get_id() ) . "'
					AND     posts.post_type     = 'shop_order'
					AND     posts.post_status   IN $statuses_sql
					AND     meta2.meta_key      = '_order_total'";
			}

			//phpcs:disable WooCommerce.Commenting.CommentHooks.MissingSinceComment
			/**
			 * Filters the SQL query used to get the combined total of all the orders from a given customer.
			 *
			 * @param string The SQL query to use.
			 * @param WC_Customer The customer to get the total spent for.
			 * @return string The actual SQL query to use.
			 */
			$sql = apply_filters( 'woocommerce_customer_get_total_spent_query', $sql, $customer );
			//phpcs:enable WooCommerce.Commenting.CommentHooks.MissingSinceComment

			$spent = $wpdb->get_var( $sql );
			//phpcs:enable WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared

			if ( ! $spent ) {
				$spent = 0;
			}
			update_user_meta( $customer->get_id(), '_money_spent', $spent );
		}

		return wc_format_decimal( $spent, 2 );
	}

	/**
	 * Search customers and return customer IDs.
	 *
	 * @param  string     $term Search term.
	 * @param  int|string $limit Limit search results.
	 * @since 3.0.7
	 *
	 * @return array
	 */
	public function search_customers( $term, $limit = '' ) {
		$results = apply_filters( 'woocommerce_customer_pre_search_customers', false, $term, $limit );
		if ( is_array( $results ) ) {
			return $results;
		}

		$query = new WP_User_Query(
			apply_filters(
				'woocommerce_customer_search_customers',
				array(
					'search'         => '*' . esc_attr( $term ) . '*',
					'search_columns' => array( 'user_login', 'user_url', 'user_email', 'user_nicename', 'display_name' ),
					'fields'         => 'ID',
					'number'         => $limit,
				),
				$term,
				$limit,
				'main_query'
			)
		);

		$query2 = new WP_User_Query(
			apply_filters(
				'woocommerce_customer_search_customers',
				array(
					'fields'     => 'ID',
					'number'     => $limit,
					'meta_query' => array(
						'relation' => 'OR',
						array(
							'key'     => 'first_name',
							'value'   => $term,
							'compare' => 'LIKE',
						),
						array(
							'key'     => 'last_name',
							'value'   => $term,
							'compare' => 'LIKE',
						),
					),
				),
				$term,
				$limit,
				'meta_query'
			)
		);

		$results = wp_parse_id_list( array_merge( (array) $query->get_results(), (array) $query2->get_results() ) );

		if ( $limit && count( $results ) > $limit ) {
			$results = array_slice( $results, 0, $limit );
		}

		return $results;
	}

	/**
	 * Get all user ids who have `billing_email` set to any of the email passed in array.
	 *
	 * @param array $emails List of emails to check against.
	 *
	 * @return array
	 */
	public function get_user_ids_for_billing_email( $emails ) {
		$emails      = array_unique( array_map( 'strtolower', array_map( 'sanitize_email', $emails ) ) );
		$users_query = new WP_User_Query(
			array(
				'fields'     => 'ID',
				'meta_query' => array(
					array(
						'key'     => 'billing_email',
						'value'   => $emails,
						'compare' => 'IN',
					),
				),
			)
		);
		return array_unique( $users_query->get_results() );
	}
}