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

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

669 lines 25.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * WCPOS REST API class.
4 *
5 * @author Paul Kilmurray <paul@kilbot.com>
6 *
7 * @see http://wcpos.com
8 * @package WCPOS\WooCommercePOS
9 */
10
11 namespace WCPOS\WooCommercePOS;
12
13 use WCPOS\WooCommercePOS\Services\Auth;
14 use WCPOS\WooCommercePOS\Services\Client_Signal;
15 use WCPOS\WooCommercePOS\Services\Settings as SettingsService;
16 use WP_HTTP_Response;
17 use WP_REST_Request;
18 use WP_REST_Response;
19 use WP_REST_Server;
20
21 /**
22 * API class.
23 */
24 class API {
25 /**
26 * WCPOS REST API namespaces.
27 */
28 public const ROUTE_NAMESPACES = array( 'wcpos/v1', 'wcpos/v2' );
29
30 /**
31 * WCPOS REST API namespaces and endpoints.
32 *
33 * @var array
34 */
35 protected $controllers = array();
36
37 /**
38 * Map of route patterns to controller keys.
39 * Built during register_routes() for use in rest_dispatch_request().
40 *
41 * @var array<string, string>
42 */
43 protected $route_map = array();
44
45 /**
46 * Route permission-gate classifier.
47 *
48 * @var API\Route_Classifier
49 */
50 protected $route_classifier;
51
52 /**
53 * Flag to check if authentication has been checked.
54 *
55 * @var bool
56 */
57 protected $is_auth_checked = false;
58
59 /**
60 * Flag to track whether WCPOS successfully authenticated the current request
61 * via its own Bearer token. Used to suppress errors from third-party JWT
62 * plugins that inspected the same Authorization header but could not validate
63 * a WCPOS-issued token with their own secret.
64 *
65 * @var bool
66 */
67 protected $authenticated_via_wcpos = false;
68
69 /**
70 * Constructor.
71 */
72 public function __construct() {
73 $this->register_routes();
74
75 /*
76 * Adds authentication to for JWT bearer tokens
77 * - We run determine_current_user at 20 to allow other plugins to run first
78 */
79 add_filter( 'determine_current_user', array( $this, 'determine_current_user' ), 20 );
80 add_filter( 'rest_authentication_errors', array( $this, 'rest_authentication_errors' ), 50, 1 );
81
82 // Adds info about the WordPress install.
83 add_filter( 'rest_index', array( $this, 'rest_index' ), 10, 1 );
84
85 // These filters allow changes to the WC REST API response.
86 add_filter( 'rest_dispatch_request', array( $this, 'rest_dispatch_request' ), 10, 4 );
87 add_filter( 'rest_pre_dispatch', array( $this, 'rest_pre_dispatch' ), 10, 3 );
88 add_filter( 'rest_post_dispatch', array( $this, 'rest_post_dispatch' ), 10, 3 );
89 }
90
91 /**
92 * Get the WCPOS REST API namespaces.
93 *
94 * @return string[] REST API namespaces.
95 */
96 public function get_route_namespaces(): array {
97 /**
98 * Filter the list of namespaces used in the WCPOS REST API.
99 *
100 * This filter is strictly additive: plugins can register additional WCPOS REST
101 * API namespaces, but the core namespaces cannot be removed — the central
102 * permission gate must keep covering every registered core route. Controllers
103 * remain responsible for declaring any special route classifications within
104 * added namespaces.
105 *
106 * @since 1.10.0
107 *
108 * @param string[] $namespaces REST API namespaces.
109 */
110 $namespaces = apply_filters( 'woocommerce_pos_rest_namespaces', self::ROUTE_NAMESPACES );
111
112 return array_values( array_unique( array_merge( self::ROUTE_NAMESPACES, (array) $namespaces ) ) );
113 }
114
115 /**
116 * Register routes for all controllers.
117 */
118 public function register_routes(): void {
119 $route_namespaces = $this->get_route_namespaces();
120 $this->route_classifier = new API\Route_Classifier( $route_namespaces );
121
122 /**
123 * Filter the list of controller classes used in the WCPOS REST API.
124 *
125 * This filter allows customizing or extending the set of controller classes that handle
126 * REST API routes for the WCPOS. By filtering these controllers, plugins can
127 * modify existing endpoints or add new controllers for additional functionality.
128 * Core legacy controllers use their versioned WCPOS\WooCommercePOS\API\V1 FQCNs.
129 *
130 * @since 1.5.0
131 *
132 * @param array $controllers Associative array of controller identifiers to their corresponding class names.
133 * - 'auth' => Fully qualified name of the class handling authentication.
134 * - 'settings' => Fully qualified name of the class handling settings.
135 * - 'cashier' => Fully qualified name of the class handling cashier management.
136 * - 'products' => Fully qualified name of the class handling products.
137 * - 'product_variations' => Fully qualified name of the class handling product variations.
138 * - 'orders' => Fully qualified name of the class handling orders.
139 * - 'customers' => Fully qualified name of the class handling customers.
140 * - 'product_tags' => Fully qualified name of the class handling product tags.
141 * - 'product_categories' => Fully qualified name of the class handling product categories.
142 * - 'taxes' => Fully qualified name of the class handling taxes.
143 * - 'shipping_methods' => Fully qualified name of the class handling shipping methods.
144 * - 'tax_classes' => Fully qualified name of the class handling tax classes.
145 * - 'order_statuses' => Fully qualified name of the class handling order statuses.
146 */
147 $classes = apply_filters(
148 'woocommerce_pos_rest_api_controllers',
149 array(
150 // WCPOS rest api controllers.
151 'auth' => API\V1\Auth::class,
152 'settings' => API\V1\Settings::class,
153 'cashier' => API\V1\Cashier::class,
154 'templates' => API\V1\Templates_Controller::class,
155 'receipts' => API\V1\Receipts_Controller::class,
156 'print_jobs' => API\V1\Print_Jobs_Controller::class,
157
158 // TODO: remove this?
159 'stores' => API\V1\Stores::class,
160 'extensions' => API\V1\Extensions::class,
161 'logs' => API\V1\Logs::class,
162 'payment_gateways' => API\V1\Payment_Gateways::class,
163 'gateway_bootstrap' => API\V1\Gateway_Bootstrap_Controller::class,
164 'checkout' => API\V1\Checkout_Controller::class,
165
166 // extend WC REST API controllers.
167 'products' => API\V1\Products_Controller::class,
168 'product_variations' => API\V1\Product_Variations_Controller::class,
169 'orders' => API\V1\Orders_Controller::class,
170 'customers' => API\V1\Customers_Controller::class,
171 'product_tags' => API\V1\Product_Tags_Controller::class,
172 'product_categories' => API\V1\Product_Categories_Controller::class,
173 'product_brands' => API\V1\Product_Brands_Controller::class,
174 'coupons' => API\V1\Coupons_Controller::class,
175 'taxes' => API\V1\Taxes_Controller::class,
176 'shipping_methods' => API\V1\Shipping_Methods_Controller::class,
177 'tax_classes' => API\V1\Tax_Classes_Controller::class,
178 'order_statuses' => API\V1\Data_Order_Statuses_Controller::class,
179 )
180 );
181
182 /**
183 * Filter the wcpos/v2 service pass-through controllers (additive to the
184 * frozen v1 surface — the legacy data controllers stay v1-only).
185 *
186 * Extensions that replace a v1 service through
187 * `woocommerce_pos_rest_api_controllers` must carry their service onto
188 * the v2 surface here with their own pass-through subclass (override
189 * `$namespace = 'wcpos/v2'`), exactly as core does — the v2 map is not
190 * derived from the v1 map, so a v1 replacement alone leaves the v2
191 * twin serving core behavior.
192 *
193 * @since 1.10.0
194 *
195 * @param array $controllers Associative array of v2 service controller class names.
196 */
197 $v2_classes = apply_filters(
198 'woocommerce_pos_rest_api_v2_controllers',
199 array(
200 'ping' => API\V2\Ping::class,
201 'echo_probe' => API\V2\Echo_Probe::class,
202 'site' => API\V2\Site::class,
203 'auth' => API\V2\Auth::class,
204 'settings' => API\V2\Settings::class,
205 'cashier' => API\V2\Cashier::class,
206 'templates' => API\V2\Templates_Controller::class,
207 'receipts' => API\V2\Receipts_Controller::class,
208 'print_jobs' => API\V2\Print_Jobs_Controller::class,
209 'stores' => API\V2\Stores::class,
210 'extensions' => API\V2\Extensions::class,
211 'logs' => API\V2\Logs::class,
212 'payment_gateways' => API\V2\Payment_Gateways::class,
213 'gateway_bootstrap' => API\V2\Gateway_Bootstrap_Controller::class,
214 'checkout' => API\V2\Checkout_Controller::class,
215 'order_email' => API\V2\Order_Email_Controller::class,
216 'shipping_methods' => API\V2\Shipping_Methods_Controller::class,
217 'tax_classes' => API\V2\Tax_Classes_Controller::class,
218 'order_statuses' => API\V2\Data_Order_Statuses_Controller::class,
219 )
220 );
221 foreach ( $v2_classes as $key => $class ) {
222 $classes[ 'v2-' . $key ] = $class;
223 }
224 $legacy_classifications = array(
225 'auth' => array( 'public' => array( '/wcpos/v1/auth/test', '/wcpos/v1/auth/refresh' ) ),
226 'print_jobs' => array( 'printer_token' => array( '/wcpos/v1/print-jobs/cloudprnt', '/wcpos/v1/print-jobs/epson-sdp' ) ),
227 'receipts' => array( 'permission_error_passthrough' => array( '/wcpos/v1/receipts/' ) ),
228 );
229
230 foreach ( $classes as $key => $class ) {
231 if ( class_exists( $class ) ) {
232 $this->controllers[ $key ] = new $class();
233 $this->controllers[ $key ]->register_routes();
234
235 if ( method_exists( $this->controllers[ $key ], 'wcpos_route_classifications' ) ) {
236 $this->route_classifier->merge( $this->controllers[ $key ]->wcpos_route_classifications() );
237 } elseif ( isset( $legacy_classifications[ $key ] ) ) {
238 $this->route_classifier->merge( $legacy_classifications[ $key ] );
239 }
240 }
241 }
242
243 // Sync classifications are independent of feature-gated route registration.
244 $this->route_classifier->merge( Sync\Api::route_classifications() );
245
246 // Build route map for use in rest_dispatch_request().
247 $rest_server = rest_get_server();
248
249 foreach ( $route_namespaces as $route_namespace ) {
250 $all_routes = $rest_server->get_routes( $route_namespace );
251
252 foreach ( $all_routes as $route_pattern => $route_handlers ) {
253 foreach ( $route_handlers as $route_handler ) {
254 $callback = $route_handler['callback'] ?? null;
255
256 // Extract the controller object from the callback.
257 $controller_obj = null;
258 if ( \is_array( $callback ) && isset( $callback[0] ) && \is_object( $callback[0] ) ) {
259 $controller_obj = $callback[0];
260 } elseif ( $callback instanceof \Closure ) {
261 // WC 10.5+ RestApiCache wraps callbacks in closures.
262 // Use reflection to extract the bound $this.
263 $ref = new \ReflectionFunction( $callback );
264 $controller_obj = $ref->getClosureThis();
265 }
266
267 if ( ! $controller_obj ) {
268 continue;
269 }
270
271 // Find which controller key this object belongs to.
272 foreach ( $this->controllers as $key => $registered_controller ) {
273 if ( $controller_obj === $registered_controller ) {
274 $this->route_map[ $route_pattern ] = $key;
275 break;
276 }
277 }
278 }
279 }
280 }
281 }
282
283 /**
284 * Check request for any login tokens.
285 *
286 * Runs at priority 20, after other plugins (e.g. third-party JWT plugins at
287 * priority 10) have had a chance to authenticate the user. If another plugin
288 * already returned a valid user ID, we trust it. Otherwise we attempt our own
289 * WCPOS Bearer-token authentication.
290 *
291 * Note: some JWT plugins pass a WP_Error through this filter when they fail to
292 * validate a Bearer token. We treat that the same as false so we can still
293 * authenticate the request with our own JWT.
294 *
295 * Note: this filter may not be called at all when WordPress has already cached
296 * the current user (WooCommerce issue #26847). The rest_authentication_errors
297 * fallback below handles that scenario.
298 *
299 * @param false|int|\WP_Error $user_id User ID if one has been determined, false otherwise.
300 *
301 * @return false|int
302 */
303 public function determine_current_user( $user_id ) {
304 $this->is_auth_checked = true;
305
306 // Trust a valid user ID set by another plugin (e.g. JWT plugin with its own token).
307 // Treat a WP_Error the same as false — another plugin rejected its own token,
308 // but we should still attempt authentication with our Bearer token.
309 if ( ! empty( $user_id ) && ! is_wp_error( $user_id ) ) {
310 return $user_id;
311 }
312
313 $result = $this->authenticate( false );
314 if ( $result && ! is_wp_error( $result ) ) {
315 $this->authenticated_via_wcpos = true;
316 return $result;
317 }
318
319 // If neither we nor another plugin authenticated the user, return false
320 // (not authenticated) rather than a WP_Error from $user_id. WordPress core
321 // expects determine_current_user to return false|int, not WP_Error.
322 // The JWT plugin's error will surface via rest_authentication_errors instead.
323 return is_wp_error( $user_id ) ? false : $user_id;
324 }
325
326 /**
327 * Handles two distinct failure modes:
328 *
329 * 1. WooCommerce issue #26847: determine_current_user may not be called when
330 * WordPress has already cached the current user. We attempt auth here as a
331 * fallback.
332 *
333 * 2. JWT plugin conflict: a third-party JWT plugin (e.g. jwt-authentication-for-wp-rest-api)
334 * sees our Bearer token, fails to validate it with its own secret, and returns
335 * a WP_Error via rest_authentication_errors at priority 10. We run at priority 50
336 * and attempt our own Bearer-token validation. If it succeeds, we clear the
337 * stale error — our authentication wins.
338 *
339 * @param mixed $errors Authentication errors.
340 *
341 * @return mixed
342 */
343 public function rest_authentication_errors( $errors ) {
344 // If there is already an error from a previous filter (e.g. a JWT plugin that
345 // rejected our Bearer token), attempt WCPOS authentication before passing it
346 // through. This covers the case where determine_current_user was skipped
347 // (WC #26847) or where the JWT plugin ran at a higher priority.
348 if ( ! empty( $errors ) ) {
349 // Only clear errors that originate from JWT authentication plugins. Errors
350 // from other mechanisms (maintenance locks, IP restrictions, etc.) should
351 // be passed through even when the WCPOS Bearer token is valid.
352 $is_jwt_plugin_error = is_wp_error( $errors ) && 0 === strpos( $errors->get_error_code(), 'jwt_auth_' );
353
354 if ( $is_jwt_plugin_error && ! $this->authenticated_via_wcpos ) {
355 $user_id = $this->authenticate( false );
356 if ( $user_id && ! is_wp_error( $user_id ) ) {
357 wp_set_current_user( $user_id );
358 $this->authenticated_via_wcpos = true;
359 }
360 }
361
362 if ( $this->authenticated_via_wcpos && $is_jwt_plugin_error ) {
363 return null;
364 }
365
366 return $errors;
367 }
368
369 // check if determine_current_user has been called.
370 if ( ! $this->is_auth_checked ) {
371 // Authentication hasn't occurred during `determine_current_user`, so check auth.
372 $user_id = $this->authenticate( false );
373 if ( $user_id && ! is_wp_error( $user_id ) ) {
374 wp_set_current_user( $user_id );
375 $this->authenticated_via_wcpos = true;
376
377 return true;
378 }
379 }
380
381 return $errors;
382 }
383
384 /**
385 * Extract the Authorization Bearer token from the request.
386 *
387 * @return false|string
388 */
389 public function get_auth_header() {
390 return Auth::instance()->get_auth_header();
391 }
392
393 /**
394 * Adds info to the WP REST API index response.
395 * - UUID
396 * - Version Info.
397 *
398 * @param WP_REST_Response $response Response data.
399 *
400 * @return WP_REST_Response
401 */
402 public function rest_index( WP_REST_Response $response ): WP_REST_Response {
403 $uuid = wcpos_get_site_uuid();
404 $response->data['uuid'] = $uuid;
405 $response->data['wp_version'] = get_bloginfo( 'version' );
406 $response->data['wc_version'] = WC()->version;
407 $response->data['wcpos_version'] = VERSION;
408 $response->data['use_jwt_as_param'] = SettingsService::instance()->use_jwt_as_param_enabled();
409
410 // Add WCPOS authentication endpoint to the response.
411 $response->data['authentication']['wcpos'] = array(
412 'endpoints' => array(
413 'authorization' => Template_Router::get_auth_url(),
414 ),
415 );
416
417 /**
418 * Remove the routes from the response.
419 *
420 * Some wordpress sites have a huge number of routes, like 2MB of data. It shouldn;t matter, but it seems
421 * to cause issues with the desktop application sometimes. We don't use the routes at the moment, so we
422 * can remove them from the response.
423 */
424 $data = $response->get_data();
425 unset( $data['routes'] );
426 $response->set_data( $data );
427
428 return $response;
429 }
430
431 /**
432 * Filters the pre-calculated result of a REST API dispatch request.
433 *
434 * Allow hijacking the request before dispatching by returning a non-empty. The returned value
435 * will be used to serve the request instead.
436 *
437 * @param mixed $result Response to replace the requested version with. Can be anything
438 * a normal endpoint can return, or null to not hijack the request.
439 * @param WP_REST_Server $server Server instance.
440 * @param WP_REST_Request $request Request used to generate the response.
441 *
442 * @return mixed
443 */
444 public function rest_pre_dispatch( $result, $server, $request ) {
445 if ( ! $this->route_classifier->in_wcpos_namespace( $request->get_route() ) ) {
446 return $result;
447 }
448
449 // Marker-gated on purpose (query var or header, NOT the rest_route arm,
450 // which matches this namespace by construction): every real POS client,
451 // old or new, carries the marker, while unmarked scanner traffic would
452 // otherwise inflate the `channel: none` tail this telemetry exists to
453 // measure (free#1752). The echo and auth lanes are excluded for the same
454 // reason: they are the gate's carve-outs, and a protocol-2 client's
455 // connect-time probes deliberately carry no signal — counting them would
456 // stamp every modern client with a daily false `none` row.
457 if ( 0 === stripos( $request->get_route(), '/wcpos/v2/' )
458 && 1 !== preg_match( '#^/wcpos/v2/(?:echo$|auth(?:/|$))#i', $request->get_route() )
459 && ( wcpos_request( 'query_var' ) || wcpos_request( 'header' ) ) ) {
460 try {
461 Client_Signal::record( $request );
462 } catch ( \Throwable $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch -- Telemetry failures are deliberately ignored.
463 // Telemetry must never interrupt a POS request.
464 }
465 }
466
467 // Latch the till's store scope for the whole request (pro#425). Set
468 // unconditionally — including to null — so a scope never leaks from one
469 // dispatch into the next. Inner `wc/v3` forwards do not reach this line
470 // (they are outside the WCPOS namespace), which is exactly right: the
471 // OUTER request owns the scope and stamps it onto the inner ones.
472 \WCPOS\WooCommercePOS\Sync\Store_Scope::set_current(
473 \WCPOS\WooCommercePOS\Sync\Store_Scope::resolve( $request )
474 );
475
476 // CORS preflights carry no credentials (browsers strip Authorization from OPTIONS),
477 // so the permission gate must never answer them with 401 — a non-2xx preflight blocks
478 // every cross-origin standalone client from the entire namespace. WP core serves
479 // OPTIONS with route metadata and Rest_Cors::rest_pre_serve_request adds the CORS headers.
480 if ( 'OPTIONS' === $request->get_method() ) {
481 return $result;
482 }
483
484 // Baseline permission gate: POS endpoints require access_woocommerce_pos; the three
485 // sync admin operations instead use their route-level manage_woocommerce check.
486 // Exempt public auth, printer-token polling, and authenticated receipt denials that need
487 // the receipt-specific error code.
488 $route = $request->get_route();
489 $has_route_specific_permission_error = is_user_logged_in() && $this->route_classifier->is_permission_error_passthrough( $route );
490 $is_public_auth_route = $this->route_classifier->is_public( $route );
491 $is_printer_token_route = $this->route_classifier->is_printer_token( $route );
492 $is_sync_admin_route = is_user_logged_in() && current_user_can( 'manage_woocommerce' ) && $this->route_classifier->is_admin_op( $route );
493
494 if ( ! $is_public_auth_route && ! $has_route_specific_permission_error && ! $is_printer_token_route && ! $is_sync_admin_route ) {
495 if ( ! current_user_can( 'access_woocommerce_pos' ) ) {
496 if ( ! is_user_logged_in() ) {
497 return new \WP_Error(
498 'woocommerce_pos_rest_unauthorized',
499 __( 'Authentication required.', 'woocommerce-pos' ),
500 array( 'status' => 401 )
501 );
502 }
503
504 return new \WP_Error(
505 'woocommerce_pos_rest_forbidden',
506 __( 'You do not have permission to access the POS.', 'woocommerce-pos' ),
507 array( 'status' => 403 )
508 );
509 }
510 }
511
512 $max_length = 10000;
513
514 // The sync sub-surface speaks its own wire contract (include = raw id
515 // list validated by its controllers); the wcpos_include/exclude rewrite
516 // below is a legacy extended-WC-controller workaround and must not
517 // mangle sync routes.
518 if ( $this->route_classifier->is_rewrite_exempt( $route ) ) {
519 return $result;
520 }
521
522 // Process 'include' parameter.
523 $include = $request->get_param( 'include' );
524 if ( $include ) {
525 $processed_include = $this->shorten_param_array( $include, $max_length );
526 $request->set_param( 'wcpos_include', $processed_include );
527 unset( $request['include'] );
528 }
529
530 // Process 'exclude' parameter.
531 $exclude = $request->get_param( 'exclude' );
532 if ( $exclude ) {
533 $processed_exclude = $this->shorten_param_array( $exclude, $max_length );
534 $request->set_param( 'wcpos_exclude', $processed_exclude );
535 unset( $request['exclude'] );
536 }
537
538 return $result;
539 }
540
541 /**
542 * Add the server pressure bucket to WCPOS REST responses.
543 *
544 * @param mixed $response REST response.
545 * @param WP_REST_Server $server REST server.
546 * @param WP_REST_Request $request REST request.
547 *
548 * @return mixed
549 */
550 public function rest_post_dispatch( $response, $server, $request ) {
551 if ( is_wp_error( $response ) ) {
552 return $response;
553 }
554
555 try {
556 if ( ! $response instanceof WP_HTTP_Response || ! $this->route_classifier->in_wcpos_namespace( $request->get_route() ) ) {
557 return $response;
558 }
559 $pressure_bucket = API\V2\Ping::pressure_bucket();
560 if ( null !== $pressure_bucket ) {
561 $response->header( 'X-WCPOS-Pressure', $pressure_bucket );
562 }
563 } catch ( \Throwable $e ) {
564 return $response;
565 }
566
567 return $response;
568 }
569
570 /**
571 * Filters the REST API dispatch request result.
572 *
573 * @param mixed $dispatch_result Dispatch result, will be used if not empty.
574 * @param WP_REST_Request $request Request used to generate the response.
575 * @param string $route Route matched for the request.
576 * @param array $handler Route handler used for the request.
577 *
578 * @return mixed
579 */
580 public function rest_dispatch_request( $dispatch_result, $request, $route, $handler ) {
581 // Only process mapped WCPOS routes.
582 if ( ! isset( $this->route_map[ $route ] ) ) {
583 return $dispatch_result;
584 }
585
586 /*
587 * POS-specific PHP settings to prevent errors in JSON and float weirdness.
588 *
589 * - error_reporting(0) - Turn off error reporting
590 * - ini_set('display_errors', 0) - Turn off error display
591 * - ini_set('precision', 10) - Set the precision of floating point numbers
592 * - ini_set('serialize_precision', 10) - Set the precision of floating point numbers for serialization
593 *
594 * This is to prevent any PHP errors from being displayed in the response.
595 *
596 * The precision settings are to prevent floating point weirdness, eg: stock_quantity 3.6 becomes 3.6000000000000001
597 */
598 error_reporting( 0 );
599 @ini_set( 'display_errors', '0' ); // phpcs:ignore WordPress.PHP.IniSet.display_errors_Disallowed -- intentionally disabling error display for POS API responses.
600 @ini_set( 'precision', '10' );
601 @ini_set( 'serialize_precision', '10' );
602
603 $key = $this->route_map[ $route ];
604 $controller = $this->controllers[ $key ] ?? null;
605
606 if ( $controller && method_exists( $controller, 'wcpos_dispatch_request' ) ) {
607 return $controller->wcpos_dispatch_request( $dispatch_result, $request, $route, $handler );
608 }
609
610 return $dispatch_result;
611 }
612
613 /**
614 * Some servers have a limit on the number of include/exclude we can use in a request.
615 * Worst thing is there is often no error message, the request returns an empty response.
616 *
617 * For example, WP Engine has a limit of 1024 characters?
618 * https://wpengine.com/support/using-dev-tools/#Long_Queries_in_wp_db
619 *
620 * @TODO - For long queries, I should find a better solution than this.
621 *
622 * @param array|string $param_value The parameter value.
623 * @param int $max_length The maximum length.
624 *
625 * @return array
626 */
627 private function shorten_param_array( $param_value, $max_length ) {
628 $param_array = \is_array( $param_value ) ? $param_value : explode( ',', $param_value );
629 $param_string = implode( ',', $param_array );
630
631 if ( \strlen( $param_string ) > $max_length ) {
632 shuffle( $param_array ); // Shuffle to randomize.
633
634 $new_param_string = '';
635 $random_param_array = array();
636
637 foreach ( $param_array as $id ) {
638 if ( \strlen( $new_param_string . $id ) < $max_length ) {
639 $new_param_string .= $id . ',';
640 $random_param_array[] = $id;
641 } else {
642 break; // Stop when maximum length is reached.
643 }
644 }
645
646 return $random_param_array;
647 }
648
649 return $param_array;
650 }
651
652 /**
653 * Check the Authorization header for a Bearer token.
654 *
655 * @param false|int $user_id User ID if one has been determined, false otherwise.
656 *
657 * @return false|int|\WP_Error
658 */
659 private function authenticate( $user_id ) {
660 $authenticated_user_id = Auth::instance()->authenticate_request();
661
662 if ( is_wp_error( $authenticated_user_id ) ) {
663 return false === $user_id ? $authenticated_user_id : $user_id;
664 }
665
666 return false === $authenticated_user_id ? $user_id : $authenticated_user_id;
667 }
668 }
669