PluginProbe
WCPOS – Point of Sale (POS) plugin for WooCommerce / 1.10.17
WCPOS – Point of Sale (POS) plugin for WooCommerce v1.10.17
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 1.9.13 All 162 releases
woocommerce-pos / includes / API / V1 / Products_Controller.php

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

708 lines 23.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Products_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_Products_Controller' ) ) {
13 return;
14 }
15
16 use Exception;
17 use WC_Data;
18 use WC_Product;
19 use WC_Product_Variable;
20 use WC_REST_Products_Controller;
21 use WCPOS\WooCommercePOS\API\Product_Search;
22 use WCPOS\WooCommercePOS\Logger;
23 use WCPOS\WooCommercePOS\Services\Barcode_Field;
24 use WCPOS\WooCommercePOS\Services\Variable_Price_Range;
25 use WCPOS\WooCommercePOS\Sync\Collection_Rules;
26 use WCPOS\WooCommercePOS\Sync\Collection_Rules_Plan;
27 use WCPOS\WooCommercePOS\Sync\Pos_Visibility;
28 use WP_Error;
29 use WP_Query;
30 use WP_REST_Request;
31 use WP_REST_Response;
32
33 /**
34 * Products controller class.
35 *
36 * @NOTE: methods not prefixed with wcpos_ will override WC_REST_Products_Controller methods
37 */
38 class Products_Controller extends WC_REST_Products_Controller {
39 use Traits\Product_Helpers;
40 use Traits\Query_Helpers;
41 use Traits\Uuid_Handler;
42 use Traits\WCPOS_REST_API;
43
44 /**
45 * Endpoint namespace.
46 *
47 * @var string
48 */
49 protected $namespace = 'wcpos/v1';
50
51 /**
52 * Allow decimal quantities.
53 *
54 * @var bool
55 */
56 protected $allow_decimal_quantities = false;
57
58 /**
59 * Store the current request object.
60 *
61 * @var WP_REST_Request|null
62 */
63 protected $wcpos_request;
64
65 /**
66 * Request keys the product Collection Rules plan reads on this lane.
67 *
68 * @var array
69 */
70 private const WCPOS_SORT_PARAM_MAP = array(
71 'orderby' => 'orderby',
72 'order' => 'order',
73 );
74
75 /**
76 * Memoized parent collection params.
77 *
78 * @var array|null
79 */
80 protected $wcpos_parent_collection_params = null;
81
82 /**
83 * Dispatch request to parent controller, or override if needed.
84 *
85 * @param mixed $dispatch_result Dispatch result, will be used if not empty.
86 * @param WP_REST_Request $request Request used to generate the response.
87 * @param string $route Route matched for the request.
88 * @param array $handler Route handler used for the request.
89 *
90 * @return mixed $dispatch_result Dispatch result, will be used if not empty.
91 */
92 public function wcpos_dispatch_request( $dispatch_result, WP_REST_Request $request, $route, $handler ) {
93 $this->wcpos_request = $request;
94
95 add_filter( 'woocommerce_rest_prepare_product_object', array( $this, 'wcpos_product_response' ), 10, 3 );
96 add_action( 'woocommerce_rest_insert_product_object', array( $this, 'wcpos_insert_product_object' ), 10, 3 );
97 add_filter( 'woocommerce_rest_product_object_query', array( $this, 'wcpos_product_query' ), 10, 2 );
98 add_filter( 'posts_search', array( $this, 'wcpos_posts_search' ), 10, 2 );
99 add_filter( 'posts_clauses', array( $this, 'wcpos_posts_clauses' ), 10, 2 );
100
101 /*
102 * Check if the request is for all products and if the 'posts_per_page' is set to -1.
103 * Optimised query for getting all product IDs.
104 */
105 if ( Bulk_ID_Fast_Path::supports_request( $request ) ) {
106 return $this->wcpos_get_all_posts( $request );
107 }
108
109 return $dispatch_result;
110 }
111
112 /**
113 * Create a single product.
114 *
115 * @param WP_REST_Request $request Full details about the request.
116 *
117 * @return WP_Error|WP_REST_Response
118 */
119 public function create_item( $request ) {
120 $invalid_meta = $this->wcpos_sanitize_meta_data_param( $request );
121 if ( is_wp_error( $invalid_meta ) ) {
122 return $invalid_meta;
123 }
124
125 return parent::create_item( $request );
126 }
127
128 /**
129 * Update a single product.
130 *
131 * @param WP_REST_Request $request Full details about the request.
132 *
133 * @return WP_Error|WP_REST_Response
134 */
135 public function update_item( $request ) {
136 $invalid_meta = $this->wcpos_sanitize_meta_data_param( $request );
137 if ( is_wp_error( $invalid_meta ) ) {
138 return $invalid_meta;
139 }
140
141 return parent::update_item( $request );
142 }
143
144 /**
145 * Add custom fields to the product schema.
146 * - Add 'barcode' property to the product schema.
147 * - Allow decimal quantities if enabled.
148 *
149 * Overrides the parent method.
150 *
151 * @return array $schema The product schema.
152 */
153 public function get_item_schema() {
154 $schema = parent::get_item_schema();
155
156 // Add the 'barcode' property if 'properties' exists and is an array.
157 if ( isset( $schema['properties'] ) && \is_array( $schema['properties'] ) ) {
158 $schema['properties']['barcode'] = array(
159 'description' => /* translators: REST API schema field label or error message. */ __( 'Barcode', 'woocommerce-pos' ),
160 'type' => 'string',
161 'context' => array( 'view', 'edit' ),
162 'readonly' => false,
163 );
164 }
165
166 // Check for 'stock_quantity' and allow decimal.
167 // Note: 'number' is the valid JSON schema type for decimals (not 'float').
168 if ( $this->wcpos_allow_decimal_quantities() &&
169 isset( $schema['properties']['stock_quantity'] ) &&
170 \is_array( $schema['properties']['stock_quantity'] ) ) {
171 $schema['properties']['stock_quantity']['type'] = 'number';
172 }
173
174 return $schema;
175 }
176
177
178 /**
179 * Modify the collection params.
180 * - Allow 'per_page' to be set to -1.
181 * - Add custom sorting options.
182 *
183 * Overrides the parent method.
184 *
185 * @return array $params The collection parameters.
186 */
187 public function get_collection_params() {
188 $params = $this->wcpos_get_parent_collection_params();
189
190 // Check if 'per_page' parameter exists and has a 'minimum' key before modifying.
191 if ( isset( $params['per_page'] ) && \is_array( $params['per_page'] ) ) {
192 $params['per_page']['minimum'] = -1;
193 }
194
195 if ( ! $this->wcpos_parent_collection_supports_param( 'brand' ) ) {
196 $params['brand'] = array(
197 'description' => /* translators: REST API collection parameter description. */ __( 'Limit result set to products assigned to brand IDs or slugs, separated by commas.', 'woocommerce-pos' ),
198 'type' => 'string',
199 'validate_callback' => 'rest_validate_request_arg',
200 );
201 }
202
203 if ( ! $this->wcpos_parent_collection_supports_param( 'brand_operator' ) ) {
204 $params['brand_operator'] = array(
205 'description' => /* translators: REST API collection parameter description. */ __( 'Operator to compare product brand terms.', 'woocommerce-pos' ),
206 'type' => 'string',
207 'enum' => array( 'in', 'not_in', 'and' ),
208 'default' => 'in',
209 'validate_callback' => 'rest_validate_request_arg',
210 );
211 }
212
213 if ( ! $this->wcpos_parent_collection_supports_param( 'category_operator' ) ) {
214 $params['category_operator'] = array(
215 'description' => /* translators: REST API collection parameter description. */ __( 'Operator to compare product category terms.', 'woocommerce-pos' ),
216 'type' => 'string',
217 'enum' => array( 'in', 'not_in', 'and' ),
218 'default' => 'in',
219 'validate_callback' => 'rest_validate_request_arg',
220 );
221 }
222
223 if ( ! $this->wcpos_parent_collection_supports_param( 'tag_operator' ) ) {
224 $params['tag_operator'] = array(
225 'description' => /* translators: REST API collection parameter description. */ __( 'Operator to compare product tag terms.', 'woocommerce-pos' ),
226 'type' => 'string',
227 'enum' => array( 'in', 'not_in', 'and' ),
228 'default' => 'in',
229 'validate_callback' => 'rest_validate_request_arg',
230 );
231 }
232
233 // Ensure 'orderby' is set and is an array before attempting to modify it.
234 if ( isset( $params['orderby']['enum'] ) && \is_array( $params['orderby']['enum'] ) ) {
235 // The POS sorts are DECLARED once, in Sync\Collection_Rules, and projected here.
236 // The v2 proxy lane claims the same list, so a sort cannot be advertised on one
237 // Read Lane and rejected on the other (#1779).
238 $new_sort_options = Collection_Rules::orderby_enum( 'products' );
239 // Merge new options, avoiding duplicates.
240 $params['orderby']['enum'] = array_unique( array_merge( $params['orderby']['enum'], $new_sort_options ) );
241 }
242
243 return $params;
244 }
245
246 /**
247 * Filter the product response.
248 *
249 * @param WP_REST_Response $response The response object.
250 * @param WC_Product $product Product data.
251 * @param WP_REST_Request $request Request object.
252 *
253 * @return WP_REST_Response $response The response object.
254 */
255 public function wcpos_product_response( WP_REST_Response $response, WC_Product $product, WP_REST_Request $request ): WP_REST_Response {
256 $data = $response->get_data();
257
258 // Add the UUID to the product response.
259 $this->maybe_add_post_uuid( $product );
260
261 // Add the barcode to the product response.
262 $data['barcode'] = $this->wcpos_get_barcode( $product );
263
264 // Check if the response has an image.
265 if ( isset( $data['images'] ) && ! empty( $data['images'] ) ) {
266 foreach ( $data['images'] as $key => $image ) {
267 // Replace the full size 'src' with the URL of the medium size image.
268 $image_id = $image['id'];
269 $medium_image_data = image_downsize( $image_id, 'medium' );
270
271 if ( $medium_image_data ) {
272 $data['images'][ $key ]['src'] = $medium_image_data[0];
273 } else {
274 $data['images'][ $key ]['src'] = $image['src'];
275 }
276 }
277 }
278
279 /*
280 * If product is variable, add the max and min prices and add them to the meta data
281 * @TODO - only need to update if there is a change
282 */
283 if ( $product->is_type( 'variable' ) && $product instanceof WC_Product_Variable ) {
284 $minimum_price = '';
285 $price_array = $this->wcpos_get_variable_product_price_ranges( $product, $minimum_price );
286
287 // A simple-to-variable conversion can leave old simple price fields on the
288 // parent. Serve the current minimum, but do not pair independent regular and
289 // sale minima from different variations into a false parent-level sale.
290 if ( array_key_exists( 'price', $data ) ) {
291 $decimals = null !== $request->get_param( 'dp' ) ? absint( $request->get_param( 'dp' ) ) : wc_get_price_decimals();
292 $data['price'] = '' === $minimum_price ? '' : wc_format_decimal( $minimum_price, $decimals );
293 }
294 foreach ( array( 'regular_price', 'sale_price' ) as $price_key ) {
295 if ( array_key_exists( $price_key, $data ) ) {
296 $data[ $price_key ] = '';
297 }
298 }
299
300 // Try encoding the array into JSON.
301 $encoded_price = wp_json_encode( $price_array );
302
303 // Check if the encoding was successful.
304 if ( false === $encoded_price ) {
305 // JSON encode failed, log the original array for debugging.
306 Logger::log( 'JSON encoding of price array failed: ' . json_last_error_msg(), $price_array );
307 } else {
308 // Update the meta data with the successfully encoded price data.
309 $product->update_meta_data( '_woocommerce_pos_variable_prices', $encoded_price );
310 }
311 }
312
313 // Parse the meta data before returning the response.
314 $data['meta_data'] = $this->wcpos_parse_meta_data( $product );
315
316 // Estimate response size and log if excessive.
317 $this->wcpos_estimate_response_size( $data, $product->get_id(), 'Product' );
318
319 // Set any changes to the response data.
320 $response->set_data( $data );
321
322 return $response;
323 }
324
325 /**
326 * Build variable product price ranges from current variation data.
327 *
328 * Thin adapter over {@see Variable_Price_Range}, THE canonical computation
329 * shared with the V2 sync read lane. This lane persists the DECIMAL rendering
330 * to `_woocommerce_pos_variable_prices` postmeta: every value formatted at the
331 * store's price precision, all three sub-ranges always present.
332 *
333 * @param WC_Product_Variable $product Variable product.
334 * @param string|null $minimum_price Unrounded filtered minimum price, passed by reference.
335 *
336 * @phpstan-param-out string $minimum_price
337 *
338 * @return array{price: array{min: string, max: string}, regular_price: array{min: string, max: string},
339 * sale_price: array{min: string, max: string}}
340 */
341 private function wcpos_get_variable_product_price_ranges( WC_Product_Variable $product, ?string &$minimum_price = null ): array {
342 $computed = Variable_Price_Range::for( $product, Variable_Price_Range::FORMAT_DECIMAL );
343 $minimum_price = $computed['minimum_price'];
344
345 return $computed['ranges'];
346 }
347
348 /**
349 * Fires after a single object is created or updated via the REST API.
350 *
351 * @param WC_Data $object Inserted object.
352 * @param WP_REST_Request $request Request object.
353 * @param bool $creating True when creating object, false when updating.
354 */
355 public function wcpos_insert_product_object( WC_Data $object, WP_REST_Request $request, $creating ): void {
356 // Update the barcode if it is set in the request.
357 if ( $request->has_param( 'barcode' ) ) {
358 Barcode_Field::write( $object, $request->get_param( 'barcode' ) );
359 }
360 }
361
362 /**
363 * Filter to adjust the WordPress search SQL query
364 * - Search for the product title and SKU and barcode
365 * - Do not search product description.
366 *
367 * @param string $search The search SQL query.
368 * @param WP_Query $wp_query The WP_Query instance (passed by reference).
369 *
370 * @return string
371 */
372 public function wcpos_posts_search( string $search, WP_Query $wp_query ) {
373 return Product_Search::posts_search( $search, $wp_query );
374 }
375
376 /**
377 * Filters all query clauses at once, for convenience.
378 *
379 * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
380 * fields (SELECT), and LIMIT clauses.
381 *
382 * @param string[] $clauses Associative array of the clauses for the query.
383 * @param WP_Query $wp_query The WP_Query instance (passed by reference).
384 */
385 public function wcpos_posts_clauses( array $clauses, WP_Query $wp_query ): array {
386 if ( ! isset( $this->wcpos_request ) ) {
387 return $clauses;
388 }
389
390 $post_type = $wp_query->query_vars['post_type'] ?? null;
391 if ( 'product' !== $post_type && ( ! \is_array( $post_type ) || ! \in_array( 'product', $post_type, true ) ) ) {
392 return $clauses;
393 }
394
395 $plan = Collection_Rules::for_request( 'products', $this->wcpos_request, self::WCPOS_SORT_PARAM_MAP );
396
397 return $plan->filter( Collection_Rules_Plan::HOOK_POSTS_CLAUSES, $clauses, $wp_query );
398 }
399
400 /**
401 * Filter the query arguments for a request.
402 *
403 * @param array $args Key value array of query var to query value.
404 * @param WP_REST_Request $request The request used.
405 *
406 * @return array $args Key value array of query var to query value.
407 */
408 public function wcpos_product_query( array $args, WP_REST_Request $request ) {
409 if ( ! empty( $request['search'] ) ) {
410 // We need to set the query up for a postmeta join.
411 add_filter( 'posts_join', array( $this, 'wcpos_posts_join_to_products_search' ), 10, 2 );
412 add_filter( 'posts_groupby', array( $this, 'wcpos_posts_groupby_product_search' ), 10, 2 );
413 }
414
415 // if POS only products are enabled, exclude online-only products.
416 if ( $this->wcpos_pos_only_products_enabled() ) {
417 add_filter( 'posts_where', array( $this, 'wcpos_posts_where_product_exclude_online_only' ), 10, 2 );
418 }
419
420 // Check for wcpos_include/wcpos_exclude parameter.
421 if ( isset( $request['wcpos_include'] ) || isset( $request['wcpos_exclude'] ) ) {
422 add_filter( 'posts_where', array( $this, 'wcpos_posts_where_product_include_exclude' ), 20, 2 );
423 }
424
425 return $args;
426 }
427
428 /**
429 * Check whether the parent WooCommerce REST controller already supports a collection param.
430 *
431 * If WooCommerce adds native REST support for Store API-style product filters, WCPOS
432 * should defer to the parent implementation instead of adding duplicate tax queries.
433 *
434 * @param string $param Collection parameter name.
435 *
436 * @return bool
437 */
438 protected function wcpos_parent_collection_supports_param( string $param ): bool {
439 $params = $this->wcpos_get_parent_collection_params();
440
441 return isset( $params[ $param ] );
442 }
443
444 /**
445 * Get parent collection params once per controller instance.
446 *
447 * @return array
448 */
449 protected function wcpos_get_parent_collection_params(): array {
450 if ( null === $this->wcpos_parent_collection_params ) {
451 $this->wcpos_parent_collection_params = parent::get_collection_params();
452 }
453
454 return $this->wcpos_parent_collection_params;
455 }
456
457 /**
458 * Parse one or more taxonomy terms from a Store API-style request parameter.
459 *
460 * @param WP_REST_Request $request The request used.
461 * @param string $param Request parameter name.
462 *
463 * @return array{field?:string,terms?:array<int,int|string>}
464 */
465 protected function wcpos_get_store_api_tax_terms_from_request( WP_REST_Request $request, string $param ): array {
466 $value = $request->get_param( $param );
467
468 if ( empty( $value ) ) {
469 return array();
470 }
471
472 $terms = array_filter( array_map( 'trim', explode( ',', (string) $value ) ) );
473 if ( empty( $terms ) ) {
474 return array();
475 }
476
477 $ids = wp_parse_id_list( $terms );
478 if ( \count( $ids ) === \count( $terms ) ) {
479 return array(
480 'field' => 'term_id',
481 'terms' => $ids,
482 );
483 }
484
485 return array(
486 'field' => 'slug',
487 'terms' => $terms,
488 );
489 }
490
491 /**
492 * Convert Store API-style taxonomy operators to WP_Query tax query operators.
493 *
494 * @param string|null $operator Store API taxonomy operator.
495 *
496 * @return string
497 */
498 protected function wcpos_get_store_api_tax_operator( ?string $operator ): string {
499 $operators = array(
500 'and' => 'AND',
501 'in' => 'IN',
502 'not_in' => 'NOT IN',
503 );
504
505 return $operators[ $operator ?? 'in' ] ?? 'IN';
506 }
507
508 /**
509 * Apply Store API taxonomy fallback query behavior for params missing in Woo REST.
510 *
511 * @param array $args Prepared query args.
512 * @param WP_REST_Request $request The request used.
513 *
514 * @return array
515 */
516 protected function wcpos_apply_store_api_tax_operator_fallbacks( array $args, WP_REST_Request $request ): array {
517 if ( ! $this->wcpos_parent_collection_supports_param( 'brand' ) ) {
518 $brand_terms = $this->wcpos_get_store_api_tax_terms_from_request( $request, 'brand' );
519 if ( isset( $brand_terms['field'], $brand_terms['terms'] ) && taxonomy_exists( 'product_brand' ) ) {
520 if ( ! isset( $args['tax_query'] ) || ! \is_array( $args['tax_query'] ) ) {
521 $args['tax_query'] = array();
522 }
523
524 $args['tax_query'][] = array(
525 'taxonomy' => 'product_brand',
526 'field' => $brand_terms['field'],
527 'terms' => $brand_terms['terms'],
528 'operator' => $this->wcpos_get_store_api_tax_operator( $request->get_param( 'brand_operator' ) ),
529 );
530 }
531 }
532
533 $operator_fallbacks = array(
534 'category_operator' => 'product_cat',
535 'tag_operator' => 'product_tag',
536 );
537 $query_params = $request->get_query_params();
538
539 foreach ( $operator_fallbacks as $param => $taxonomy ) {
540 if ( $this->wcpos_parent_collection_supports_param( $param ) || ! array_key_exists( $param, $query_params ) ) {
541 continue;
542 }
543
544 if ( ! isset( $args['tax_query'] ) || ! \is_array( $args['tax_query'] ) ) {
545 continue;
546 }
547
548 $args['tax_query'] = $this->wcpos_replace_tax_query_operator_for_taxonomy(
549 $args['tax_query'],
550 $taxonomy,
551 $this->wcpos_get_store_api_tax_operator( $request->get_param( $param ) )
552 );
553 }
554
555 return $args;
556 }
557
558 /**
559 * Replace a tax query clause operator for one taxonomy.
560 *
561 * @param array $tax_query Tax query clauses.
562 * @param string $taxonomy Taxonomy to match.
563 * @param string $operator WP_Tax_Query operator.
564 *
565 * @return array
566 */
567 protected function wcpos_replace_tax_query_operator_for_taxonomy( array $tax_query, string $taxonomy, string $operator ): array {
568 foreach ( $tax_query as $key => $clause ) {
569 if ( ! \is_array( $clause ) || ! isset( $clause['taxonomy'] ) || $taxonomy !== $clause['taxonomy'] ) {
570 continue;
571 }
572
573 $tax_query[ $key ]['operator'] = $operator;
574 }
575
576 return $tax_query;
577 }
578
579 /**
580 * Filters the JOIN clause of the query.
581 *
582 * @param string $join The JOIN clause of the query.
583 * @param WP_Query $query The WP_Query instance (passed by reference).
584 *
585 * @return string
586 */
587 public function wcpos_posts_join_to_products_search( string $join, WP_Query $query ) {
588 return Product_Search::posts_join( $join, $query );
589 }
590
591 /**
592 * Filters the GROUP BY clause of the query.
593 *
594 * @param string $groupby The GROUP BY clause of the query.
595 * @param WP_Query $query The WP_Query instance (passed by reference).
596 *
597 * @return string
598 */
599 public function wcpos_posts_groupby_product_search( string $groupby, WP_Query $query ) {
600 return Product_Search::posts_groupby( $groupby, $query );
601 }
602
603 /**
604 * Filters the WHERE clause of the query.
605 *
606 * Exclusion set and feature gate both come from Sync\Pos_Visibility, the single POS visibility
607 * authority.
608 *
609 * @param string $where The WHERE clause of the query.
610 * @param WP_Query $query The WP_Query instance (passed by reference).
611 *
612 * @return string
613 */
614 public function wcpos_posts_where_product_exclude_online_only( string $where, WP_Query $query ) {
615 global $wpdb;
616
617 return ( new Pos_Visibility() )->apply_to_sql_where( $where, "{$wpdb->posts}.ID", Pos_Visibility::PRODUCTS );
618 }
619
620 /**
621 * Filters the WHERE clause of the query.
622 *
623 * @param string $where The WHERE clause of the query.
624 * @param WP_Query $query The WP_Query instance (passed by reference).
625 *
626 * @return string
627 */
628 public function wcpos_posts_where_product_include_exclude( string $where, WP_Query $query ) {
629 global $wpdb;
630
631 // Handle 'wcpos_include'.
632 if ( ! empty( $this->wcpos_request['wcpos_include'] ) ) {
633 $include_ids = array_map( 'intval', (array) $this->wcpos_request['wcpos_include'] );
634 $ids_format = implode( ',', array_fill( 0, \count( $include_ids ), '%d' ) );
635 $where .= $wpdb->prepare( " AND {$wpdb->posts}.ID IN ($ids_format) ", $include_ids ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name and format are safe.
636 }
637
638 // Handle 'wcpos_exclude'.
639 if ( ! empty( $this->wcpos_request['wcpos_exclude'] ) ) {
640 $exclude_ids = array_map( 'intval', (array) $this->wcpos_request['wcpos_exclude'] );
641 $ids_format = implode( ',', array_fill( 0, \count( $exclude_ids ), '%d' ) );
642 $where .= $wpdb->prepare( " AND {$wpdb->posts}.ID NOT IN ($ids_format) ", $exclude_ids ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name and format are safe.
643 }
644
645 return $where;
646 }
647
648
649 /**
650 * Returns array of all product ids, name.
651 *
652 * @param WP_REST_Request $request Full details about the request.
653 *
654 * @return WP_Error|WP_REST_Response
655 */
656 public function wcpos_get_all_posts( $request ) {
657 global $wpdb;
658
659 $start_time = microtime( true );
660 $select_fields = Bulk_ID_Fast_Path::select_fields( $request, 'ID', 'post_modified_gmt' );
661
662 $sql = "SELECT DISTINCT {$select_fields} FROM {$wpdb->posts}";
663 $sql .= " WHERE post_type = 'product' AND post_status = 'publish'";
664
665 // Drop the POS-hidden ids — Sync\Pos_Visibility owns both the exclusion set and the feature gate.
666 $sql = ( new Pos_Visibility() )->apply_to_sql_where( $sql, 'ID', Pos_Visibility::PRODUCTS );
667
668 $modified_after_date = Bulk_ID_Fast_Path::modified_after_gmt( $request );
669 if ( $modified_after_date ) {
670 $sql .= $wpdb->prepare( ' AND post_modified_gmt > %s', $modified_after_date );
671 }
672
673 $sql = Bulk_ID_Fast_Path::append_id_filters_sql( $sql, $request, "{$wpdb->posts}.ID" );
674 $sql .= " ORDER BY {$wpdb->posts}.post_date DESC";
675
676 try {
677 $results = $wpdb->get_results( $sql, ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- SQL is built with prepare() above.
678
679 return Bulk_ID_Fast_Path::response( $this, $results, $start_time );
680 } catch ( Exception $e ) {
681 return Bulk_ID_Fast_Path::fetch_error( 'Error fetching product data: ' . $e->getMessage(), 'Error fetching product data.' );
682 }
683 }
684
685 /**
686 * Prepare objects query.
687 *
688 * @param WP_REST_Request $request Full details about the request.
689 *
690 * @return array|WP_Error
691 */
692 protected function prepare_objects_query( $request ) {
693 $args = parent::prepare_objects_query( $request );
694 $args = $this->wcpos_apply_store_api_tax_operator_fallbacks( $args, $request );
695
696 /*
697 * The POS sorts (`sku`, `barcode`, `stock_quantity`, `stock_status`) are NOT
698 * mapped onto `meta_key` + `orderby => meta_value` here any more. That pair
699 * INNER JOINs postmeta, so it dropped every product with no value for the key —
700 * a sort acting as a filter (#1779 follow-up). `Sync\Collection_Rules` declares
701 * them and `wcpos_posts_clauses()` applies them as a LEFT JOIN, on this lane and
702 * on the v2 proxy alike.
703 */
704
705 return $args;
706 }
707 }
708