PluginProbe
WCPOS – Point of Sale (POS) plugin for WooCommerce / 1.10.10
WCPOS – Point of Sale (POS) plugin for WooCommerce v1.10.10
1.10.19 1.10.18 1.10.17 1.10.16 1.10.15 1.10.13 1.10.14 1.10.12 1.10.11 1.10.10 1.10.9 1.10.8 untagged-3d9b7ccddc54df87c672 1.10.7 1.10.6 1.10.5 1.10.3 1.10.4 1.10.2 1.10.1 1.10.0 1.9.17 1.9.15 1.9.16 1.9.14 All 163 releases
woocommerce-pos / includes / API / V1 / Customers_Controller.php

Customers_Controller.php in WCPOS – Point of Sale (POS) plugin for WooCommerce 1.10.10, at includes/API/V1/Customers_Controller.php

962 lines 33.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Customers_Controller.
4 *
5 * @package WCPOS\WooCommercePOS
6 */
7
8 namespace WCPOS\WooCommercePOS\API\V1;
9
10 \defined( 'ABSPATH' ) || die;
11
12 if ( ! class_exists( 'WC_REST_Customers_Controller' ) ) {
13 return;
14 }
15
16 use Exception;
17 use WC_Customer;
18 use WC_REST_Customers_Controller;
19 use WCPOS\WooCommercePOS\Logger;
20 use WCPOS\WooCommercePOS\Services\Customer_Account_Guard;
21 use WCPOS\WooCommercePOS\Services\Settings as SettingsService;
22 use WCPOS\WooCommercePOS\Services\Tax_Id_Reader;
23 use WCPOS\WooCommercePOS\Services\Tax_Id_Types;
24 use WCPOS\WooCommercePOS\Services\Tax_Id_Writer;
25 use WCPOS\WooCommercePOS\Sync\Collection_Rules;
26 use WP_Error;
27 use WP_REST_Request;
28 use WP_REST_Response;
29 use WP_User;
30 use WP_User_Query;
31
32 /**
33 * Product Tgas controller class.
34 *
35 * @NOTE: methods not prefixed with wcpos_ will override WC_REST_Customers_Controller methods
36 */
37 class Customers_Controller extends WC_REST_Customers_Controller {
38 use Traits\Query_Helpers;
39 use Traits\Uuid_Handler;
40 use Traits\WCPOS_REST_API;
41
42 /**
43 * Endpoint namespace.
44 *
45 * @var string
46 */
47 protected $namespace = 'wcpos/v1';
48
49 /**
50 * Store user search results for merging with meta_query search results.
51 *
52 * @var array
53 */
54 protected $wcpos_user_search_results = array();
55
56 /**
57 * Store the request object for use in lifecycle methods.
58 *
59 * @var WP_REST_Request
60 */
61 protected $wcpos_request;
62
63 /**
64 * Dispatch request to parent controller, or override if needed.
65 *
66 * @param mixed $dispatch_result Dispatch result, will be used if not empty.
67 * @param WP_REST_Request $request Request used to generate the response.
68 * @param string $route Route matched for the request.
69 * @param array $handler Route handler used for the request.
70 */
71 public function wcpos_dispatch_request( $dispatch_result, WP_REST_Request $request, $route, $handler ) {
72 $this->wcpos_request = $request;
73
74 add_filter( 'woocommerce_rest_prepare_customer', array( $this, 'wcpos_customer_response' ), 10, 3 );
75 add_filter( 'woocommerce_rest_customer_query', array( $this, 'wcpos_customer_query' ), 10, 2 );
76 add_filter( 'is_protected_meta', array( $this, 'wcpos_allow_uuid_meta' ), 10, 3 );
77
78 /*
79 * Check if the request is for all customers and if the 'posts_per_page' is set to -1.
80 * Optimised query for getting all customer IDs.
81 */
82 if ( Bulk_ID_Fast_Path::supports_request( $request ) ) {
83 return $this->wcpos_get_all_posts( $request );
84 }
85
86 return $dispatch_result;
87 }
88
89 /**
90 * Add custom fields to the product schema.
91 */
92 public function get_item_schema() {
93 $schema = parent::get_item_schema();
94
95 // Check and remove email format validation from the billing property.
96 if ( isset( $schema['properties']['billing']['properties']['email']['format'] ) ) {
97 unset( $schema['properties']['billing']['properties']['email']['format'] );
98 }
99
100 // Add structured tax_ids property (TaxId[]).
101 $schema['properties']['tax_ids'] = array(
102 'description' => /* translators: REST API schema field label or error message. */ __( 'Customer tax IDs.', 'woocommerce-pos' ),
103 'type' => 'array',
104 'context' => array( 'view', 'edit' ),
105 'items' => array(
106 'type' => 'object',
107 'properties' => array(
108 'type' => array(
109 'type' => 'string',
110 'enum' => Tax_Id_Types::all_types(),
111 'description' => /* translators: REST API schema field label or error message. */ __( 'Tax ID type.', 'woocommerce-pos' ),
112 ),
113 'value' => array(
114 'type' => 'string',
115 'description' => /* translators: REST API schema field label or error message. */ __( 'Tax ID value.', 'woocommerce-pos' ),
116 ),
117 'country' => array(
118 'type' => array( 'string', 'null' ),
119 'description' => __( 'ISO 3166-1 alpha-2 country code.', 'woocommerce-pos' ),
120 ),
121 'label' => array(
122 'type' => array( 'string', 'null' ),
123 'description' => /* translators: REST API schema field label or error message. */ __( 'Optional human-readable label.', 'woocommerce-pos' ),
124 ),
125 ),
126 ),
127 );
128
129 return $schema;
130 }
131
132 /**
133 * Check if a given request has access to create a customer.
134 *
135 * WC checks promote_users (< 9.9) or create_customers (9.9+). The POS
136 * fallback checks only the version-appropriate capability so it matches
137 * the toggle shown on the Access settings page.
138 *
139 * @param WP_REST_Request $request Full details about the request.
140 *
141 * @return WP_Error|bool
142 */
143 public function create_item_permissions_check( $request ) {
144 $permission = parent::create_item_permissions_check( $request );
145
146 if ( is_wp_error( $permission ) ) {
147 $customer_create_cap = version_compare( WC()->version, '9.9', '>=' )
148 ? 'create_customers'
149 : 'promote_users';
150
151 if ( current_user_can( $customer_create_cap ) ) {
152 return true;
153 }
154 }
155
156 return $permission;
157 }
158
159 /**
160 * Check if a given request has access to update a customer.
161 *
162 * WCPOS never widens WooCommerce's credential fence, which refuses
163 * email/password changes on non-customer roles. The guard additionally
164 * keeps non-admins off staff accounts, testing capabilities rather than
165 * WooCommerce's first-role-only test.
166 *
167 * @param WP_REST_Request $request Full details about the request.
168 *
169 * @return WP_Error|bool
170 */
171 public function update_item_permissions_check( $request ) {
172 return $this->wcpos_guarded_permissions_check(
173 (int) $request['id'],
174 function () use ( $request ) {
175 return parent::update_item_permissions_check( $request );
176 }
177 );
178 }
179
180 /**
181 * Check if a given request has access to delete a customer.
182 *
183 * WooCommerce refuses deleting a user whose role is outside its allowed
184 * list, but it reads only the FIRST role, so an administrator who also
185 * holds the customer role is deleted by any POS user with delete_users.
186 * The guard closes that by capability.
187 *
188 * @param WP_REST_Request $request Full details about the request.
189 *
190 * @return WP_Error|bool
191 */
192 public function delete_item_permissions_check( $request ) {
193 return $this->wcpos_guarded_permissions_check(
194 (int) $request['id'],
195 function () use ( $request ) {
196 return parent::delete_item_permissions_check( $request );
197 }
198 );
199 }
200
201 /**
202 * Run WooCommerce's own check behind the staff account guard.
203 *
204 * The guard runs first and can only refuse. When it clears the target,
205 * that target's roles are allowed through WooCommerce's shop_manager
206 * role-name restriction for the duration of the check, so a cleared
207 * subscriber or membership-plugin role is judged by capability.
208 *
209 * @param int $target_id Target user ID.
210 * @param callable $check Returns WooCommerce's verdict.
211 *
212 * @return WP_Error|bool
213 */
214 private function wcpos_guarded_permissions_check( int $target_id, callable $check ) {
215 if ( ! Customer_Account_Guard::can_modify( get_current_user_id(), $target_id ) ) {
216 return Customer_Account_Guard::denial();
217 }
218
219 $restore = Customer_Account_Guard::allow_target_roles( $target_id );
220
221 try {
222 return $check();
223 } finally {
224 $restore();
225 }
226 }
227
228 /**
229 * Add extra fields to WP_REST_Controller::get_collection_params().
230 * - add new fields to the 'orderby' enum list.
231 * - default the 'role' filter to every user, matching the proxy Read Lane.
232 */
233 public function get_collection_params() {
234 $params = parent::get_collection_params();
235
236 /*
237 * The POS customer space is every user on this site, not only the users
238 * holding the `customer` role. `wcpos_get_all_posts()` has always enumerated
239 * `wp_users` unfiltered, and the proxy Read Lane defaults `role` to `all`
240 * (see Customers_Proxy_Behavior); only this paged list inherited wc/v3's
241 * `role => customer` default, so the same query answered differently on each
242 * lane and the bulk id set did not match the list it was meant to describe.
243 * Defaulting here is the parity fix; an explicit `role` still narrows.
244 */
245 if ( isset( $params['role'] ) ) {
246 $params['role']['default'] = 'all';
247 }
248
249 // Check if 'orderby' is set and is an array before modifying it.
250 if ( isset( $params['orderby'] ) && \is_array( $params['orderby']['enum'] ) ) {
251 /*
252 * A PROJECTION of the customer sort rows, so this schema enum and the proxy
253 * lane's claim list cannot disagree about which sorts WCPOS implements.
254 */
255 $new_orderby_options = Collection_Rules::orderby_enum( 'customers' );
256 foreach ( $new_orderby_options as $option ) {
257 if ( ! \in_array( $option, $params['orderby']['enum'], true ) ) {
258 $params['orderby']['enum'][] = $option;
259 }
260 }
261 }
262
263 // Add 'roles' filter, this allows us to filter by multiple roles.
264 $params['roles'] = array(
265 'description' => __( 'Filter customers by roles.', 'woocommerce-pos' ),
266 'type' => 'array',
267 'items' => array(
268 'type' => 'string',
269 ),
270 'required' => false,
271 );
272
273 return $params;
274 }
275
276 /**
277 * Create a single item.
278 *
279 * @param WP_REST_Request $request Full details about the request.
280 *
281 * @return WP_Error|WP_REST_Response
282 */
283 public function create_item( $request ) {
284 $invalid_meta = $this->wcpos_sanitize_meta_data_param( $request );
285 if ( is_wp_error( $invalid_meta ) ) {
286 return $invalid_meta;
287 }
288
289 $valid_email = $this->wcpos_validate_billing_email( $request );
290 if ( is_wp_error( $valid_email ) ) {
291 return $valid_email;
292 }
293
294 /*
295 * Generate a password for the new user.
296 * Add filter for get_option key 'woocommerce_registration_generate_password' to ensure it is set to 'yes'.
297 */
298 add_filter(
299 'pre_option_woocommerce_registration_generate_password',
300 function () {
301 return 'yes';
302 }
303 );
304
305 /*
306 * Optionally generate a username from the customer's email address.
307 * Reads the POS 'generate_username' general setting and overrides the
308 * store-level 'woocommerce_registration_generate_username' option so the
309 * POS behaviour is independent of the online-checkout setting.
310 */
311 $generate_username = SettingsService::instance()->generate_username_enabled();
312 add_filter(
313 'pre_option_woocommerce_registration_generate_username',
314 function () use ( $generate_username ) {
315 return $generate_username ? 'yes' : 'no';
316 }
317 );
318
319 // Proceed with the parent method to handle the creation.
320 $response = parent::create_item( $request );
321 $this->wcpos_persist_tax_ids_from_request( $response, $request );
322
323 return $response;
324 }
325
326 /**
327 * Update a single order.
328 *
329 * @param WP_REST_Request $request Full details about the request.
330 *
331 * @return WP_Error|WP_REST_Response
332 */
333 public function update_item( $request ) {
334 $invalid_meta = $this->wcpos_sanitize_meta_data_param( $request );
335 if ( is_wp_error( $invalid_meta ) ) {
336 return $invalid_meta;
337 }
338
339 $valid_email = $this->wcpos_validate_billing_email( $request );
340 if ( is_wp_error( $valid_email ) ) {
341 return $valid_email;
342 }
343
344 // Proceed with the parent method to handle the creation.
345 $response = parent::update_item( $request );
346 $this->wcpos_persist_tax_ids_from_request( $response, $request );
347
348 return $response;
349 }
350
351 /**
352 * Persist `tax_ids` from a create/update request via Tax_Id_Writer.
353 *
354 * No-op when the request did not include `tax_ids`, the response is an
355 * error, or the resolved user ID is invalid.
356 *
357 * @param mixed $response Response from the parent controller.
358 * @param WP_REST_Request $request Original request.
359 */
360 protected function wcpos_persist_tax_ids_from_request( $response, WP_REST_Request $request ): void {
361 if ( ! ( $response instanceof WP_REST_Response ) ) {
362 return;
363 }
364 $tax_ids = $request->get_param( 'tax_ids' );
365 if ( ! \is_array( $tax_ids ) ) {
366 return;
367 }
368
369 $data = $response->get_data();
370 $user_id = isset( $data['id'] ) ? (int) $data['id'] : 0;
371 if ( $user_id <= 0 ) {
372 return;
373 }
374
375 ( new Tax_Id_Writer() )->write_for_user( $user_id, $tax_ids );
376
377 // Reflect persisted list in the response.
378 $data['tax_ids'] = ( new Tax_Id_Reader() )->read_for_user( $user_id );
379 $response->set_data( $data );
380 }
381
382 /**
383 * Validate billing email.
384 * NOTE: we have removed the format check to allow empty email addresses.
385 *
386 * @param WP_REST_Request $request The REST request object.
387 *
388 * @return bool|WP_Error
389 */
390 public function wcpos_validate_billing_email( WP_REST_Request $request ) {
391 // Your custom validation logic for the request data.
392 $billing = $request['billing'] ?? null;
393 $email = \is_array( $billing ) ? ( $billing['email'] ?? null ) : null;
394
395 if ( ! \is_null( $email ) && '' !== $email && ! is_email( $email ) ) {
396 return new WP_Error(
397 'rest_invalid_param',
398 // translators: Use default WordPress translation.
399 __( 'Invalid email address.', 'woocommerce-pos' ),
400 array( 'status' => 400 )
401 );
402 }
403
404 return true;
405 }
406
407 /**
408 * Filter customer data returned from the REST API.
409 *
410 * @param WP_REST_Response $response The response object.
411 * @param WP_User $user_data User object used to create response.
412 * @param WP_REST_Request $request Request object.
413 */
414 public function wcpos_customer_response( WP_REST_Response $response, WP_User $user_data, WP_REST_Request $request ): WP_REST_Response {
415 $data = $response->get_data();
416
417 // Add the uuid to the response.
418 $this->maybe_add_user_uuid( $user_data );
419
420 /*
421 * Add the customer meta data to the response
422 *
423 * In the WC REST Customers Controller -> get_formatted_item_data_core function, the customer's
424 * meta_data is only added for administrators. I assume this is for privacy/security reasons?
425 *
426 * Even for administrators, meta data starting with '_' will be filtered out.
427 * We need to add the uuid meta_data to the response for all cashiers and also non-protected meta.
428 *
429 * This means we let of junk meta_data into the response, but at least we don't block data and allow
430 * saving of meta_data.
431 *
432 * @TODO - add filter settings to block/allow meta_data keys
433 */
434 try {
435 $customer = new WC_Customer( $user_data->ID );
436 $raw_meta_data = $customer->get_meta_data();
437
438 // Monitor meta count.
439 $this->wcpos_monitor_meta_count( $customer, $raw_meta_data );
440
441 $filtered_meta_data = array_filter(
442 $raw_meta_data,
443 function ( $meta ) {
444 return ! is_protected_meta( $meta->key, 'user' );
445 }
446 );
447
448 // Convert to WC REST API expected format.
449 $data['meta_data'] = array_map(
450 function ( $meta ) {
451 return array(
452 'id' => $meta->id,
453 'key' => $meta->key,
454 'value' => $meta->value,
455 );
456 },
457 array_values( $filtered_meta_data )
458 );
459 } catch ( Exception $e ) {
460 Logger::log( 'Error getting customer meta data: ' . $e->getMessage() );
461 }
462
463 // Add structured tax_ids list (read fallback across legacy plugin meta keys).
464 $data['tax_ids'] = ( new Tax_Id_Reader() )->read_for_user( $user_data->ID );
465
466 // Estimate response size and log if excessive.
467 $this->wcpos_estimate_response_size( $data, $user_data->ID, 'Customer' );
468
469 // Set any changes to the response data.
470 $response->set_data( $data );
471
472 return $response;
473 }
474
475 /**
476 * Returns array of all customer ids.
477 *
478 * Note: user queries are a little more complicated than post queries, for example,
479 * multisite would return all users from all sites, not just the current site.
480 * Also, querying by role is not as simple as querying by post type.
481 *
482 * @param WP_REST_Request $request Full details about the request.
483 *
484 * @return WP_Error|WP_REST_Response
485 */
486 public function wcpos_get_all_posts( $request ) {
487 global $wpdb;
488
489 $start_time = microtime( true );
490 $modified_after = Bulk_ID_Fast_Path::modified_after_timestamp( $request );
491 $has_modified_after = null !== $modified_after;
492 $id_with_modified_date = Bulk_ID_Fast_Path::wants_modified_date( $request );
493
494 $args = array(
495 'fields' => array( 'ID', 'user_registered' ), // Return only the ID and registered date.
496 // 'role__in' => 'all', // @TODO: could be an array of roles, like ['customer', 'cashier'].
497 );
498 $args = Bulk_ID_Fast_Path::apply_id_filters_to_args( $args, $request );
499
500 /*
501 * The user query is too complex to do a direct sql query, eg: multisite would return all users from all sites,
502 * not just the current site. Also, querying by role is not as simple as querying by post type.
503 *
504 * For now we get all user ids and all 'last_update' meta values, then combine them into an array of objects.
505 */
506 try {
507 $user_query = new WP_User_Query( $args );
508 $users = $user_query->get_results();
509 $last_updates = array();
510
511 if ( $id_with_modified_date || $has_modified_after ) {
512 $query = "
513 SELECT user_id, meta_value
514 FROM $wpdb->usermeta
515 WHERE meta_key = 'last_update'
516 ";
517
518 // If modified_after param is set, add the condition to the query.
519 if ( $has_modified_after ) {
520 $query .= $wpdb->prepare( ' AND meta_value > %d', (int) $modified_after );
521 }
522
523 $last_update_results = $wpdb->get_results( $query ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Query is prepared conditionally above.
524
525 // Manually create the associative array of user_id => last_update.
526 foreach ( $last_update_results as $result ) {
527 $last_updates[ $result->user_id ] = is_numeric( $result->meta_value ) ? gmdate( 'Y-m-d\TH:i:s', (int) $result->meta_value ) : null;
528 }
529 }
530
531 /**
532 * Performance notes:
533 * - Using a generator is faster than array_map when dealing with large datasets.
534 * - If date is in the format 'Y-m-d H:i:s' we just do preg_replace to 'Y-m-d\TH:i:s',
535 * rather than using wc_rest_prepare_date_response
536 *
537 * This resulted in execution time of 10% of the original time.
538 *
539 * If the modified_after param is set, we don't need to loop through the entire user list.
540 * The last_update_results array will only contain the users that have been modified after the given date.
541 * We just need to check they are valid user ids, this sucks, but there could be orphaned last_update meta values.
542 */
543 $formatted_results = array();
544
545 if ( $has_modified_after ) {
546 foreach ( $users as $user ) {
547 if ( isset( $last_updates[ $user->ID ] ) ) {
548 $user_info = array( 'id' => (int) $user->ID );
549 if ( $id_with_modified_date ) {
550 $user_info['date_modified_gmt'] = $last_updates[ $user->ID ];
551 }
552 $formatted_results[] = $user_info;
553 }
554 }
555 } else {
556 $formatted_results = iterator_to_array(
557 ( function () use ( $users, $last_updates, $id_with_modified_date ) {
558 foreach ( $users as $user ) {
559 $user_info = array( 'id' => (int) $user->ID );
560 if ( $id_with_modified_date ) {
561 if ( isset( $last_updates[ $user->ID ] ) && ! empty( $last_updates[ $user->ID ] ) ) {
562 $user_info['date_modified_gmt'] = $last_updates[ $user->ID ];
563 } else {
564 $user_info['date_modified_gmt'] = null; // users can have null date_modified_gmt.
565 }
566 }
567 yield $user_info;
568 }
569 } )()
570 );
571 }
572
573 return Bulk_ID_Fast_Path::response( $this, $formatted_results, $start_time, false );
574 } catch ( Exception $e ) {
575 return Bulk_ID_Fast_Path::fetch_error( 'Error fetching order IDs: ' . $e->getMessage(), 'Error fetching customer IDs.' );
576 }
577 }
578
579 /**
580 * Filter arguments, before passing to WP_User_Query, when querying users via the REST API.
581 *
582 * @param array $prepared_args Array of arguments for WP_User_Query.
583 * @param WP_REST_Request $request The current request.
584 *
585 * @return array $prepared_args Array of arguments for WP_User_Query.
586 */
587 public function wcpos_customer_query( array $prepared_args, WP_REST_Request $request ): array {
588 $query_params = $request->get_query_params();
589
590 // add modified_after date_modified_gmt.
591 if ( isset( $query_params['modified_after'] ) && '' !== $query_params['modified_after'] ) {
592 $timestamp = strtotime( $query_params['modified_after'] );
593
594 /*
595 * `last_update` holds a Unix timestamp, but it is stored as usermeta text and
596 * `WP_Meta_Query` defaults an untyped clause to CHAR — which compares it as a
597 * string. Timestamps only sort the same way as strings while they are the same
598 * length, so a cutoff from before 2001-09-09 (nine digits) drops every current
599 * customer, whose timestamp is ten digits starting with a `1`: `'1787465309' >
600 * '946684800'` is false, character by character. NUMERIC casts to SIGNED and
601 * compares the numbers, which is what the bulk-id fast path below has always
602 * done by binding the same value with `%d`.
603 */
604 $prepared_args['meta_query'] = $this->wcpos_merge_meta_queries(
605 array(
606 array(
607 'key' => 'last_update',
608 'value' => $timestamp ? (string) $timestamp : '',
609 'compare' => '>',
610 'type' => 'NUMERIC',
611 ),
612 ),
613 $prepared_args['meta_query'] ?? array()
614 );
615 }
616
617 // Handle orderby cases.
618 if ( isset( $query_params['orderby'] ) ) {
619 switch ( $query_params['orderby'] ) {
620 case 'first_name':
621 $prepared_args['meta_key'] = 'first_name';
622 $prepared_args['orderby'] = 'meta_value';
623
624 break;
625
626 case 'last_name':
627 $prepared_args['meta_key'] = 'last_name';
628 $prepared_args['orderby'] = 'meta_value';
629
630 break;
631
632 case 'email':
633 $prepared_args['orderby'] = 'user_email';
634
635 break;
636
637 case 'role':
638 /*
639 * Roles live in the serialized `wp_capabilities` usermeta
640 * (eg. a:1:{s:8:"customer";b:1;}), so a plain `orderby =>
641 * meta_value` sorts by that opaque string — dominated by the
642 * s:N: length prefix, not the role. Defer to a pre_user_query
643 * callback that ranks by role hierarchy instead. We leave
644 * `orderby`/`meta_key` untouched (no WP meta join to fight)
645 * and mark the query so the callback only touches ours.
646 */
647 $prepared_args['_wcpos_orderby_role'] = true;
648 add_action( 'pre_user_query', array( $this, 'wcpos_orderby_role' ) );
649
650 break;
651
652 case 'username':
653 $prepared_args['orderby'] = 'user_login';
654
655 break;
656
657 default:
658 break;
659 }
660 }
661
662 // Handle search. A whitespace-only search has no terms, so treat it as no search at all.
663 if ( isset( $query_params['search'] ) && 0 !== preg_match( '/\S/u', (string) $query_params['search'] ) ) {
664 $search_keyword = $query_params['search'];
665
666 /*
667 * It seems that you can't search by user_email, user_login etc and meta_query at the same time.
668 *
669 * We will unset the search param and add a hook to modify the user query to search the user table
670 */
671 unset( $prepared_args['search'] );
672 $prepared_args['_wcpos_search'] = $search_keyword; // store the search keyword for later use.
673 add_action( 'pre_user_query', array( $this, 'wcpos_search_user_table' ) );
674 } elseif ( isset( $query_params['search'] ) ) {
675 unset( $prepared_args['search'] );
676 }
677
678 // Handle include/exclude.
679 if ( isset( $request['wcpos_include'] ) || isset( $request['wcpos_exclude'] ) ) {
680 add_action( 'pre_user_query', array( $this, 'wcpos_include_exclude_users_by_id' ) );
681 }
682
683 // Filter by roles (this is a comma separated list of roles).
684 if ( ! empty( $request['roles'] ) && \is_array( $request['roles'] ) ) {
685 $roles = array_map( 'sanitize_text_field', $request['roles'] );
686 $prepared_args['role__in'] = $roles;
687 // remove $prepared_args['role'] to prevent it from overriding $prepared_args['role__in'].
688 unset( $prepared_args['role'] );
689 }
690
691 return $prepared_args;
692 }
693
694 /**
695 * Combine two meta_query arrays.
696 *
697 * Moved here from the Query_Helpers trait, of which this controller was the only caller.
698 *
699 * @param array $meta_query1 First meta query array.
700 * @param array $meta_query2 Second meta query array.
701 *
702 * @return array Combined meta query array.
703 */
704 private function wcpos_merge_meta_queries( $meta_query1, $meta_query2 ) {
705 // If either meta_query is empty, return the other.
706 if ( empty( $meta_query1 ) ) {
707 return $meta_query2;
708 }
709 if ( empty( $meta_query2 ) ) {
710 return $meta_query1;
711 }
712
713 // Check if both meta_queries have 'AND' as their top-level relation.
714 if ( isset( $meta_query1['relation'] ) && 'AND' === $meta_query1['relation'] &&
715 isset( $meta_query2['relation'] ) && 'AND' === $meta_query2['relation'] ) {
716 // Remove the 'relation' element and combine the arrays.
717 unset( $meta_query1['relation'], $meta_query2['relation'] );
718 $combined = array_merge( $meta_query1, $meta_query2 );
719 array_unshift( $combined, array( 'relation' => 'AND' ) );
720
721 return $combined;
722 }
723
724 // If both meta_queries are not empty and do not both have 'AND', combine them with 'AND' relation.
725 return array(
726 'relation' => 'AND',
727 $meta_query1,
728 $meta_query2,
729 );
730 }
731
732 /**
733 * Add the customer search conditions to the user query.
734 *
735 * @param WP_User_Query $query The WP_User_Query instance (passed by reference).
736 */
737 public function wcpos_search_user_table( $query ): void {
738 global $wpdb;
739
740 // Remove the hook.
741 remove_action( 'pre_user_query', array( $this, 'wcpos_search_user_table' ) );
742
743 $query_params = $query->query_vars;
744
745 /*
746 * Only act on the customer query we prepared. WordPress fires pre_user_query for every
747 * WP_User_Query, and this callback can survive onto an unrelated one if our own query is
748 * short-circuited (eg. via the users_pre_query filter) before it runs. Without our search
749 * marker there is nothing to do, and appending a condition would corrupt that other query.
750 */
751 if ( empty( $query_params['_wcpos_search'] ) ) {
752 return;
753 }
754
755 $terms = preg_split( '/\s+/u', (string) $query_params['_wcpos_search'], -1, PREG_SPLIT_NO_EMPTY );
756
757 /*
758 * Whitespace-only searches are filtered out before the hook is added, so reaching this
759 * point means the string could not be split (eg. malformed UTF-8). We can't honour the
760 * search, and falling through would hand back the entire customer list, so match nothing.
761 */
762 if ( false === $terms || empty( $terms ) ) {
763 $query->query_where .= ' AND 1 = 0';
764
765 return;
766 }
767
768 $terms = array_slice( $terms, 0, 10 );
769
770 $meta_keys = array_merge(
771 array(
772 'first_name',
773 'last_name',
774 'billing_first_name',
775 'billing_last_name',
776 'billing_email',
777 'billing_company',
778 'billing_phone',
779 ),
780 Tax_Id_Reader::fallback_user_meta_keys()
781 );
782
783 $meta_key_placeholders = implode( ', ', array_fill( 0, \count( $meta_keys ), '%s' ) );
784 $term_groups = array();
785
786 foreach ( $terms as $term ) {
787 $like = '%' . $wpdb->esc_like( $term ) . '%';
788 $prepare_args = array_merge( array( $like, $like, $like ), $meta_keys, array( $like ) );
789
790 // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table names come from $wpdb; $meta_key_placeholders is a generated list of %s placeholders, and the keys themselves are passed to prepare() as arguments.
791 $term_groups[] = $wpdb->prepare(
792 "( {$wpdb->users}.user_email LIKE %s
793 OR {$wpdb->users}.user_login LIKE %s
794 OR {$wpdb->users}.display_name LIKE %s
795 OR EXISTS (
796 SELECT 1
797 FROM {$wpdb->usermeta} AS wcpos_search_meta
798 WHERE wcpos_search_meta.user_id = {$wpdb->users}.ID
799 AND wcpos_search_meta.meta_key IN ($meta_key_placeholders)
800 AND wcpos_search_meta.meta_value LIKE %s
801 )
802 )",
803 $prepare_args
804 );
805 // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
806 }
807
808 $query->query_where .= ' AND ( ' . implode( ' AND ', $term_groups ) . ' )';
809 }
810
811 /**
812 * Include or exclude users by ID.
813 *
814 * @param WP_User_Query $query The WP_User_Query instance (passed by reference).
815 */
816 public function wcpos_include_exclude_users_by_id( $query ): void {
817 global $wpdb;
818
819 // Remove the hook.
820 remove_action( 'pre_user_query', array( $this, 'wcpos_include_exclude_users_by_id' ) );
821
822 // Handle 'wcpos_include'.
823 if ( ! empty( $this->wcpos_request['wcpos_include'] ) ) {
824 $include_ids = array_map( 'intval', (array) $this->wcpos_request['wcpos_include'] );
825 $ids_format = implode( ',', array_fill( 0, \count( $include_ids ), '%d' ) );
826 // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- $ids_format is a safe placeholder string.
827 $query->query_where .= $wpdb->prepare( " AND {$wpdb->users}.ID IN ($ids_format) ", $include_ids );
828 }
829
830 // Handle 'wcpos_exclude'.
831 if ( ! empty( $this->wcpos_request['wcpos_exclude'] ) ) {
832 $exclude_ids = array_map( 'intval', (array) $this->wcpos_request['wcpos_exclude'] );
833 $ids_format = implode( ',', array_fill( 0, \count( $exclude_ids ), '%d' ) );
834 // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- $ids_format is a safe placeholder string.
835 $query->query_where .= $wpdb->prepare( " AND {$wpdb->users}.ID NOT IN ($ids_format) ", $exclude_ids );
836 }
837 }
838
839 /**
840 * Order the customer query by role hierarchy.
841 *
842 * Roles are stored in the serialized `wp_capabilities` usermeta, which SQL
843 * cannot meaningfully ORDER BY (the value's leading `s:N:` length prefix, not
844 * the role name, dominates a string sort). Instead of extracting the slug we
845 * LEFT JOIN that meta row and rank it with a CASE ladder built from the known
846 * role hierarchy, matching each role by its quoted, serialization-safe slug
847 * (`"customer"`) so the length prefix is irrelevant.
848 *
849 * Design decisions:
850 * - Hierarchy, not alphabetical/label: the POS customer space is every WP
851 * user (#1379) and is overwhelmingly `customer`. A cashier sorting by role
852 * wants staff grouped and predictably separated from buyers, not scattered
853 * across the alphabet, so we rank by privilege (administrator → subscriber),
854 * unknown/custom/no-role users last.
855 * - Multi-role → highest privilege: a user who is both shop_manager and
856 * customer is treated as staff. The ladder tests the most-privileged role
857 * first, so the highest role a user holds fixes their position — which is
858 * more correct than WP core's "first role in the array" (insertion order).
859 * - Ties (same rank) fall back to `user_login` for a deterministic order.
860 *
861 * @param WP_User_Query $query The WP_User_Query instance (passed by reference).
862 */
863 public function wcpos_orderby_role( $query ): void {
864 global $wpdb;
865
866 // Remove the hook.
867 remove_action( 'pre_user_query', array( $this, 'wcpos_orderby_role' ) );
868
869 /*
870 * Only act on the customer query we prepared. WordPress fires
871 * pre_user_query for every WP_User_Query, and this callback can survive
872 * onto an unrelated one if our own query is short-circuited (eg. via the
873 * users_pre_query filter) before it runs. See wcpos_search_user_table.
874 */
875 if ( empty( $query->query_vars['_wcpos_orderby_role'] ) ) {
876 return;
877 }
878
879 $order = ( isset( $query->query_vars['order'] ) && 'DESC' === strtoupper( (string) $query->query_vars['order'] ) )
880 ? 'DESC'
881 : 'ASC';
882
883 // Role privilege hierarchy, highest first. Matched on the quoted slug so
884 // the serialized length prefix (s:N:) never affects the comparison.
885 // `cashier` is WCPOS's own registered POS-staff role (see Activator), so
886 // it groups with staff — above the content roles — rather than falling
887 // into the trailing bucket with customers/subscribers.
888 $hierarchy = array(
889 'administrator',
890 'shop_manager',
891 'cashier',
892 'editor',
893 'author',
894 'contributor',
895 'customer',
896 'subscriber',
897 );
898
899 /*
900 * Capabilities meta is blog-prefixed (wp_capabilities on the main site,
901 * wp_<id>_capabilities on subsites), so resolve it via get_blog_prefix()
902 * rather than hardcoding — the POS customer space is the current site's
903 * users.
904 */
905 $cap_key = $wpdb->get_blog_prefix() . 'capabilities';
906
907 // LEFT JOIN so users with no capabilities row still sort (into the
908 // trailing "everyone else" bucket). Each user has at most one such row,
909 // so the join never multiplies rows or corrupts the total count.
910 //
911 // Guard against a duplicate alias: `woocommerce_rest_customer_query` can
912 // carry more than one registered instance of this controller (each adds
913 // its own pre_user_query action), so this callback may run several times
914 // for one query. Appending the join unconditionally would emit two
915 // `wcpos_role_meta` aliases and fail with "Not unique table/alias".
916 if ( false === strpos( $query->query_from, 'wcpos_role_meta' ) ) {
917 // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table names come from $wpdb; the meta key is passed to prepare() as %s.
918 $query->query_from .= $wpdb->prepare(
919 " LEFT JOIN {$wpdb->usermeta} AS wcpos_role_meta ON ( {$wpdb->users}.ID = wcpos_role_meta.user_id AND wcpos_role_meta.meta_key = %s )",
920 $cap_key
921 );
922 }
923
924 $when_sql = '';
925 $when_args = array();
926 $rank = 1;
927 foreach ( $hierarchy as $role_slug ) {
928 $when_sql .= ' WHEN wcpos_role_meta.meta_value LIKE %s THEN ' . $rank;
929 $when_args[] = '%' . $wpdb->esc_like( '"' . $role_slug . '"' ) . '%';
930 ++$rank;
931 }
932 // $rank is now the "everyone else" bucket (unknown/custom/no role).
933 $case_sql = "CASE{$when_sql} ELSE {$rank} END";
934
935 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $case_sql is built from a static role whitelist; the only variables are %s LIKE placeholders passed to prepare().
936 $order_by = $wpdb->prepare( $case_sql, $when_args );
937
938 // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- $order_by is prepared above; $order is a validated ASC|DESC literal; the table/column come from $wpdb.
939 $query->query_orderby = "ORDER BY ( {$order_by} ) {$order}, {$wpdb->users}.user_login ASC";
940 }
941
942 /**
943 * Allow the _woocommerce_pos_uuid meta key to be saved via the REST API.
944 *
945 * By default, meta keys starting with '_' are protected and cannot be set via the REST API.
946 * We need to allow our UUID meta key so that UUIDs sent from the POS app are preserved.
947 *
948 * @param bool $protected Whether the meta key is considered protected.
949 * @param string $meta_key The meta key being checked.
950 * @param string $meta_type The type of object the meta is for (post, user, etc.).
951 *
952 * @return bool Whether the meta key should be protected.
953 */
954 public function wcpos_allow_uuid_meta( $protected, $meta_key, $meta_type ) {
955 if ( '_woocommerce_pos_uuid' === $meta_key && 'user' === $meta_type ) {
956 return false;
957 }
958
959 return $protected;
960 }
961 }
962