PluginProbe
WCPOS – Point of Sale (POS) plugin for WooCommerce / 1.10.3
WCPOS – Point of Sale (POS) plugin for WooCommerce v1.10.3
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.3, at includes/API/V1/Products_Controller.php

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