PluginProbe
WCPOS – Point of Sale (POS) plugin for WooCommerce / 1.10.18
WCPOS – Point of Sale (POS) plugin for WooCommerce v1.10.18
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 / Products_Controller.php

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

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