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 / Init.php

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

513 lines 26.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Load required classes.
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\Admin\Consent;
14 use WCPOS\WooCommercePOS\Admin\Menu;
15 use WCPOS\WooCommercePOS\Services\Auth as AuthService;
16 use WCPOS\WooCommercePOS\Services\Extensions;
17 use WCPOS\WooCommercePOS\Services\Receipt_Snapshot_Store;
18 use WCPOS\WooCommercePOS\Services\Settings as SettingsService;
19
20 /**
21 * Init class.
22 */
23 class Init {
24 /**
25 * Constructor — the plugin's entire `plugins_loaded` hook wiring.
26 *
27 * Reached from {@see Activator::init()}, which runs on `plugins_loaded` at the
28 * default priority 10. Everything that must exist before `init` fires — most
29 * importantly the `determine_current_user` pair — has to be registered here.
30 *
31 * NOT PURE WIRING. Constructing this class also, in statement order:
32 * `require_once`s `wcpos-functions.php` and `wcpos-store-functions.php`;
33 * registers the `wc_pos_user_uuid_locks` global cache group; READS the sync
34 * schema-latch option; WRITES options through
35 * `Config_Fingerprint::maybe_cleanup_legacy_options()` (one-time, latched on
36 * its own version option); and SCHEDULES a daily cron event through
37 * `Sync_Journal_Purge::register_hooks()`. Anything that constructs `Init` —
38 * a test included — inherits all of that.
39 *
40 * ## How to read the ordering table
41 *
42 * A priority number decides ordering on its own, wherever in this method it
43 * happens to be written. Statement order is load-bearing ONLY when two
44 * callbacks share a hook AND a priority: WordPress then runs them in
45 * registration order. Exactly one such pair exists here, and it is marked
46 * ORDER-CRITICAL (STATEMENT ORDER) below — do not move it.
47 *
48 * Priorities that live in the callee (`Meta_Normalizer` at 5, `Revision` at 9,
49 * the proxy stampers at 10) are listed at the value they actually register,
50 * not at the position of the call in this method. Reordering those statements
51 * changes nothing; changing those numbers changes everything.
52 *
53 * "Why" is recovered from `git log -S` / `git blame` where a reason was
54 * recorded. Where none was, the entry says **unknown** rather than guessing.
55 *
56 * ## Ordering table
57 *
58 * | # | Hook | Callback | Pri | Order | Why that priority |
59 * |---|------|----------|-----|-------|-------------------|
60 * | 1 | `activated_plugin`, `upgrader_process_complete`, `admin_enqueue_scripts`, `admin_notices`, `rest_api_init` | `Admin\Consent` (5 callbacks) | 10 | irrelevant | Default. What matters is that `Consent` is built during `plugins_loaded`, so its lifecycle hooks exist before an activation/update request fires them. |
61 * | 2 | `woocommerce_pos_rest_api_controllers` | `Sync\Api::register_controllers` | 10 | irrelevant | Default; sole callback. |
62 * | 3 | `wcpos_integrity_digest_rebuild` | `Sync\Integrity_Digest::run_scheduled_rebuild` | 10 | irrelevant | Default; sole callback. Registered OUTSIDE the schema latch, so an already-scheduled rebuild still has a callback while the latch is down. |
63 * | 4 | `woocommerce_pos_sync_proxy_response`, `..._serialized_product`, `..._serialized_order` | `Sync\Meta_Normalizer::normalize` | **5** | **ORDER-CRITICAL** | Must precede `Revision` at 9 so the stamped revision bytes equal what the write path recomputes from a bare `wc/v3` re-read. See `Sync\Augmentation_Pipeline` class docblock and `Sync\Meta_Normalizer::register_hooks()`. Kept out of the pipeline because it also serves the ORDER lane. |
64 * | 5 | `woocommerce_pos_sync_serialized_order` | `Sync\Pos_Uuid::stamp_serialized_record` | 10 | order-critical (by number) | After `Meta_Normalizer` at 5, in step with the product lane's stampers. |
65 * | 6 | `woocommerce_pos_sync_order_pull_payloads` | `Sync\Integrity_Digest::stamp_proxy_order_digests` | 10 | irrelevant | Default; sole callback on that filter. |
66 * | 7 | `woocommerce_pos_sync_proxy_response` | `Sync\Revision::stamp_proxy_revisions` (via `Augmentation_Pipeline::install()`) | **9** | **ORDER-CRITICAL** | Between `Meta_Normalizer` (5) and the uuid/digest stampers (10). Revision must hash the normalized-but-not-yet-augmented payload. |
67 * | 8 | `woocommerce_pos_sync_proxy_response`, `..._serialized_product` | `Proxy_Uuid_Stamper`, `Integrity_Digest` digest stampers, pipeline projections | 10 | order-critical (by number) | Preserved verbatim from the hand-wiring the pipeline replaced, so third-party code hooking either public filter still runs where it always did. |
68 * | 9 | `woocommerce_before_product_object_save`, `woocommerce_before_product_variation_object_save` | `Sync\Pos_Uuid::stamp_on_save` | 10 | irrelevant | Default. The HOOK is the design (before the data store writes, so the uuid lands in the same save); the number is not. Registered unconditionally — identity is core, not an observer. |
69 * | 9a | `untrashed_post`, `woocommerce_untrash_order` | `Sync\Pos_Uuid::recheck_ownership_after_untrash`, `::recheck_order_ownership_after_untrash` | 10 | irrelevant | Default. Re-proves uuid ownership when a record leaves the trash — the one seam a native restore passes through (#1805, ADR 0038). Unconditional for the same reason as row 9; the journal and digest observers (rows 10, 12) share both hooks at the same priority once the latch is set, and nothing depends on the order. |
70 * | 10 | 32 catalogue/customer/order hooks | `Sync\Sync_Journal` (33 callbacks) | 10 | irrelevant | Default throughout. |
71 * | 10b | `delete_option` plus `pre_update_option_*`, `update_option_*`, `add_option_*`, `delete_option_*` for the two `Pos_Visibility::source_options()` | `Sync\Visibility_Observer` (9 callbacks) | 10 | irrelevant | Default. Appends the journal row for a record entering or leaving the POS servable set — the transition the sequence-log stream relies on, since it drops a hidden record's update rows. `delete_option` is the generic PRE-delete action (the per-option form fires after) and is gated on the option name inside the callback. Registered after `Sync_Journal` only because it writes through it; the constructor also runs the observer's one-time tombstone seed. |
72 * | 11 | `wcpos_sync_journal_purge` | `Sync\Sync_Journal_Purge::run_purge` | 10 | irrelevant | Cron callback; sole listener. This call also SCHEDULES the daily event. |
73 * | 12 | 21 catalogue/customer/order hooks (a subset of row 10's) | `Sync\Integrity_Digest` | 10 | unknown | Default. Shares every one of its hooks with `Sync_Journal` at the same priority, so the journal always runs first — no code found that depends on that, but nothing pins it either. |
74 * | 13 | `init` | `Init::init` | 10 | **ORDER-CRITICAL, CROSS-PLUGIN** | Default. **Pro registers its own `init` at 20** (`woocommerce-pos-pro/includes/Init.php:32`) so free's services exist first. Raising free's number silently breaks Pro; nothing on either side tests it. |
75 * | 14 | `rest_api_init` | `Init::init_rest_api` | **20** | **ORDER-CRITICAL, CROSS-PLUGIN** | Free's own reason: unknown — the number dates to the initial commit (8f2b9eac, 2021-03-16). It is load-bearing anyway: **Pro registers `rest_api_init` at 9**, commented "Before the free version" (`woocommerce-pos-pro/includes/Init.php:33`). Untested on both sides. |
76 * | 15 | `query_vars` | `Init::query_vars` | 10 | irrelevant | Default; appends one var. |
77 * | 16 | `pre_update_option_woocommerce_pos_pro_settings_license` | `Init::remove_license_transient` | 10 | irrelevant | Default. The reentrancy guard, not the priority, is what makes it safe (f33b8d655). |
78 * | 17 | ~~`rest_pre_serve_request`~~ | *(removed)* | — | — | Init no longer publishes any part of the REST wire contract. This registration and its handler moved to `Rest_Cors::register_hooks()`, which registers at **20** — after core's `rest_send_cors_headers` at 10 — so WCPOS is the last writer on the lanes it owns. The old `5` had no recorded reason; the new number does. |
79 * | 18 | `send_headers` | `Init::send_headers` | 99 | unknown | Introduced by 62da70551 ("fix WPSEO integration"). The commit records no reason for the number beyond running late. |
80 * | 19 | `send_headers` | `Init::remove_x_frame_options` | **9999** | **ORDER-CRITICAL** | Must run AFTER security plugins have set `X-Frame-Options`, because it works by `header_remove()` (80ee545a5). A smaller number lets the plugin set the header again afterwards. |
81 * | 20 | `determine_current_user` | `Services\Core_Order_Audit_Guard::record_prior_authentication` | **20** | **ORDER-CRITICAL (STATEMENT ORDER)** | See below. |
82 * | 21 | `rest_pre_dispatch` | `Services\Core_Order_Audit_Guard::rest_pre_dispatch` | 10 | irrelevant | Default; reads what row 20 recorded. |
83 * | 22 | `woocommerce_update_coupon` | `Sync\Coupon_Modified_Date::touch` | 10 | irrelevant | Default. `Sync_Journal::record_coupon_updated` shares the hook and priority (row 10) and is registered first, but the journal timestamps rows with the wall clock, not the coupon's `post_modified`, so neither ordering changes an outcome. |
84 * | 23 | `determine_current_user` | `Init::determine_current_user_early` | **20** | **ORDER-CRITICAL (STATEMENT ORDER)** | See below. |
85 * | 24 | `admin_init` | `Services\Lifecycle_Events::flush_pending`, `::maybe_schedule_refresh` | 10 | irrelevant | Default. `admin_init` because both need a fully booted admin request: one sends install/upgrade events recorded before the plugin was loaded enough to send them, the other schedules row 25. Both check consent first and cost nothing on a site that opted out. |
86 * | 25 | `wcpos_analytics_group_refresh` | `Services\Lifecycle_Events::refresh_group_properties` | 10 | irrelevant | Default; sole listener. Unlike row 11, this call does NOT schedule the event — scheduling lives in row 24 so that withdrawing consent unschedules it. |
87 *
88 * ## The one pair where statement order is the whole mechanism
89 *
90 * Rows 20 and 23 share `determine_current_user` AND priority 20, so insertion
91 * order — and nothing else — decides which runs first. 20 puts both after
92 * WordPress core's own handlers, which `default-filters.php` registers before
93 * any plugin loads: `wp_validate_auth_cookie` at 10, then
94 * `wp_validate_logged_in_cookie` and `wp_validate_application_password`, both
95 * at 20 and therefore both ahead of these two.
96 *
97 * The guard must run FIRST. It records into `pre_wcpos_user_id` whichever user
98 * some EARLIER filter had already authenticated; a non-zero value means the
99 * request proved itself with a cookie or application password, so
100 * `Core_Order_Audit_Guard::is_wcpos_jwt_authenticated()` returns false and the
101 * request keeps its normal power over order meta.
102 *
103 * Swap the two statements and the guard records the user WCPOS's own JWT filter
104 * just authenticated. `pre_wcpos_user_id` is then non-zero on every
105 * token-authenticated request, `is_wcpos_jwt_authenticated()` returns false for
106 * all of them, and forged `_pos_*` audit meta on `/wc/v3/orders` is accepted.
107 * It fails OPEN, silently, on a route no smoke test touches.
108 *
109 * Pinned by `tests/includes/Test_Init_Hook_Wiring.php`, which asserts the two
110 * callbacks' ARRAY POSITIONS inside `callbacks[20]` — asserting priorities
111 * would pass on the broken order.
112 */
113 public function __construct() {
114 // global helper functions.
115 require_once PLUGIN_PATH . 'includes/wcpos-functions.php';
116 require_once PLUGIN_PATH . 'includes/wcpos-store-functions.php';
117 wp_cache_add_global_groups( 'wc_pos_user_uuid_locks' );
118
119 // Tracking consent pop-up + callout. Registered here (during
120 // plugins_loaded) so its lifecycle hooks (activated_plugin,
121 // upgrader_process_complete) are in place before those actions
122 // fire on a plugin activation or update request.
123 new Consent();
124 add_filter( 'woocommerce_pos_rest_api_controllers', array( \WCPOS\WooCommercePOS\Sync\Api::class, 'register_controllers' ) );
125 add_action( \WCPOS\WooCommercePOS\Sync\Integrity_Digest::REBUILD_HOOK, array( \WCPOS\WooCommercePOS\Sync\Integrity_Digest::class, 'run_scheduled_rebuild' ) );
126 // Gate on the schema latch, not a live Health probe: the latch is only
127 // set AFTER install verified every table (latch-after-verify), so a
128 // per-request SHOW TABLES sweep buys nothing — and a table lost after
129 // latching is already survivable (observer writes fail open and the
130 // REST health gate 503s the sync endpoints).
131 $sync_schema_latched = \WCPOS\WooCommercePOS\Sync\Api::SCHEMA_VERSION === get_option( \WCPOS\WooCommercePOS\Sync\Api::SCHEMA_OPTION, null );
132 if ( $sync_schema_latched ) {
133 // Normalize structured meta at priority 5, before revision stamps at 9
134 // and UUID, digest, and variable-price stamps at priority 10. Kept out
135 // of the augmentation pipeline because it also serves the order lane.
136 \WCPOS\WooCommercePOS\Sync\Meta_Normalizer::register_hooks();
137 add_filter( 'woocommerce_pos_sync_serialized_order', array( \WCPOS\WooCommercePOS\Sync\Pos_Uuid::class, 'stamp_serialized_record' ), 10, 3 );
138 // ONE seam for both product read lanes: the batch catalog proxy and the
139 // per-object serializer. Every stamper is declared once inside; both
140 // public filter names stay live as projections of it. The order pull
141 // lane's digest stamper is wired there too — it was hand-added here,
142 // under this same latch, which made the pipeline's single-wiring-site
143 // claim untrue.
144 \WCPOS\WooCommercePOS\Sync\Augmentation_Pipeline::install();
145 }
146
147 // Identity is core, not an observer benchmark variable: every product is
148 // born with a UUID even before the schema latch is healthy. The before-save
149 // hook writes it in the same save.
150 \WCPOS\WooCommercePOS\Sync\Pos_Uuid::register_hooks();
151
152 if ( $sync_schema_latched ) {
153 ( new \WCPOS\WooCommercePOS\Sync\Sync_Journal() )->register_hooks();
154 $visibility_observer = new \WCPOS\WooCommercePOS\Sync\Visibility_Observer();
155 $visibility_observer->register_hooks();
156 $visibility_observer->maybe_seed_hidden_tombstones();
157 ( new \WCPOS\WooCommercePOS\Sync\Sync_Journal_Purge() )->register_hooks();
158 ( new \WCPOS\WooCommercePOS\Sync\Integrity_Digest() )->register_hooks();
159 }
160
161 ( new \WCPOS\WooCommercePOS\Sync\Config_Fingerprint() )->maybe_cleanup_legacy_options();
162
163 // Init hooks.
164 add_action( 'init', array( $this, 'init' ) );
165 add_action( 'rest_api_init', array( $this, 'init_rest_api' ), 20 );
166 add_filter( 'query_vars', array( $this, 'query_vars' ) );
167
168 // Remove this once Pro settings have been moved to the new settings service.
169 add_filter( 'pre_update_option_woocommerce_pos_pro_settings_license', array( self::class, 'remove_license_transient' ), 10, 2 );
170
171 // The REST wire contract — CORS and shared-cache defeat — has a single
172 // owner. Registered unconditionally, from here rather than from the
173 // X-WCPOS-gated API class, because preflights carry no marker and the
174 // relay's consent route is served without constructing API.
175 Rest_Cors::register_hooks();
176
177 // Non-REST API discoverability: the HEAD probe against the homepage.
178 add_action( 'send_headers', array( $this, 'send_headers' ), 99, 1 );
179 add_action( 'send_headers', array( $this, 'remove_x_frame_options' ), 9999, 1 );
180
181 /*
182 * Add the global JWT authentication filter and its core-route audit guard.
183 *
184 * Hook order: plugins_loaded -> init (determine_current_user) -> rest_api_init
185 *
186 * This filter runs at priority 20, after WordPress core's cookie auth handlers.
187 * It must be registered here (during plugins_loaded) because determine_current_user
188 * fires during 'init', which is BEFORE rest_api_init where our API class loads.
189 * Because it authenticates WCPOS Bearer tokens on EVERY
190 * REST request (marked or not), the audit-meta guard for core routes
191 * must be registered just as unconditionally — never from the
192 * X-WCPOS-gated API class, whose marker an attacker simply omits.
193 * Registering it first lets its priority-20 provenance filter run after
194 * core's cookie handlers but before WCPOS's JWT filter.
195 */
196 ( new Services\Core_Order_Audit_Guard() )->register_hooks();
197
198 // Coupon post-date touch. Unconditional and lane-agnostic on purpose: a
199 // meta-only coupon edit (amount, discount_type, usage limits) never moves
200 // post_modified, and the client's catalogue replication is date-based
201 // (?modified_after, filtered by WooCommerce on post_modified_gmt), so an
202 // untouched coupon is invisible to every other till. That is true whether
203 // the edit came from the POS, wp-admin, WP-CLI or another plugin — so this
204 // sits outside the schema latch above because it does not use the v2 sync
205 // tables.
206 \WCPOS\WooCommercePOS\Sync\Coupon_Modified_Date::register_hooks();
207
208 add_filter( 'determine_current_user', array( $this, 'determine_current_user_early' ), 20 );
209
210 // Install lifecycle reporting. Registered last: it adds no filter that
211 // anything else orders against, and appending keeps the ordering table
212 // above in statement order. Deliberately NOT before the pair above —
213 // rows 20 and 23 are decided by insertion order alone.
214 ( new Services\Lifecycle_Events() )->register_hooks();
215 }
216
217 /**
218 * Clear cached data that depends on the Pro license.
219 *
220 * @param mixed $value The new option value.
221 * @param mixed $old_value The previous option value (false when unset).
222 *
223 * @return mixed
224 */
225 public static function remove_license_transient( $value, $old_value = false ) {
226 // Pro's updater can react to the update_plugins deletion by reading —
227 // and, when the stored instance id is blank, re-saving — the license
228 // option, which re-enters this filter. Without the guard that cycle is
229 // unbounded and OOMs the first license activation on a fresh install.
230 static $clearing = false;
231 if ( $clearing ) {
232 return $value;
233 }
234 $clearing = true;
235 delete_transient( 'woocommerce_pos_pro_license_status' );
236
237 // The update caches bind to the license key and activation state. A
238 // write that changes neither — e.g. Pro's read-side instance mint —
239 // must not wipe update_plugins: Pro reacts to that deletion by
240 // clearing its own update-data cache, which empties the payload of an
241 // update check that is in flight when the mint occurs.
242 $old = \is_array( $old_value ) ? $old_value : array();
243 $new = \is_array( $value ) ? $value : array();
244 if (
245 (string) ( $old['key'] ?? '' ) !== (string) ( $new['key'] ?? '' )
246 || ! empty( $old['activated'] ) !== ! empty( $new['activated'] )
247 ) {
248 delete_site_transient( 'update_plugins' );
249 }
250 $clearing = false;
251
252 return $value;
253 }
254
255 /**
256 * Early authentication check for JWT tokens.
257 *
258 * This runs BEFORE rest_api_init, so we can authenticate users before WP REST API
259 * permission callbacks run. This is especially important for authorization via
260 * query parameter (?authorization=Bearer...) which some servers require.
261 *
262 * Note: We don't check for X-WCPOS header here because:
263 * 1. The header check uses getallheaders() which may not work in all environments
264 * 2. JWT authentication should work regardless - the token itself is proof of WCPOS usage
265 * 3. Invalid tokens (non-WCPOS) will fail validation anyway
266 *
267 * @param false|int $user_id User ID if one has been determined, false otherwise.
268 *
269 * @return false|int User ID if authenticated, original value otherwise.
270 */
271 public function determine_current_user_early( $user_id ) {
272 // Skip if user already authenticated.
273 if ( ! empty( $user_id ) ) {
274 return $user_id;
275 }
276
277 $authenticated_user_id = AuthService::instance()->authenticate_request();
278 if ( false === $authenticated_user_id || is_wp_error( $authenticated_user_id ) ) {
279 return $user_id;
280 }
281
282 return $authenticated_user_id;
283 }
284
285 /**
286 * Load the required resources.
287 */
288 public function init(): void {
289 $this->init_common();
290 $this->init_frontend();
291 $this->init_admin();
292 $this->init_integrations();
293 }
294
295 /**
296 * Loads the POS API and duck punches the WC REST API.
297 */
298 public function init_rest_api(): void {
299 $is_wcpos_request = woocommerce_pos_request();
300
301 if ( $is_wcpos_request ) {
302 if ( ! wcpos_request( 'header' ) && ! wcpos_request( 'query_var' ) ) {
303 // Namespace-detected only: routes still register, but surface
304 // that a proxy/WAF is stripping the X-WCPOS marker.
305 $this->log_unmarked_wcpos_rest_request();
306 }
307 new API();
308 } else {
309 // Queue the registration at a later priority of the SAME
310 // rest_api_init pass this method runs on (priority 20), so
311 // register_rest_route() executes during the action as WP requires.
312 // When this method is called outside the action (tests), the
313 // add_action is simply inert.
314 add_action( 'rest_api_init', array( $this, 'register_public_relay_routes' ), 30 );
315 new WC_API();
316 }
317 }
318
319 /**
320 * Register the relay's public consent-callback route for unmarked requests.
321 *
322 * The WCPOS Cloud Print relay proves site consent by fetching
323 * print-jobs/relay-verification WITHOUT the WCPOS request marker, so this
324 * single public route must exist even when the full WCPOS API is not
325 * loaded. Everything else stays behind the marker.
326 */
327 public function register_public_relay_routes(): void {
328 register_rest_route(
329 SHORT_NAME . '/v1',
330 '/print-jobs/relay-verification',
331 array(
332 'methods' => 'GET',
333 'callback' => array( new API\V1\Print_Jobs_Controller(), 'relay_verification' ),
334 'permission_callback' => '__return_true',
335 )
336 );
337 }
338
339 /**
340 * Log requests for a WCPOS namespace that omitted the request marker.
341 *
342 * Namespace detection registers the routes anyway; this surfaces that a
343 * proxy/WAF is stripping the X-WCPOS marker so misconfigured hosts stay
344 * visible in the logs. Warnings are limited by API version to avoid
345 * allowing repeated unauthenticated requests to flood WooCommerce logs.
346 */
347 private function log_unmarked_wcpos_rest_request(): void {
348 global $wp;
349
350 $route = isset( $wp->query_vars['rest_route'] )
351 ? '/' . ltrim( sanitize_text_field( wp_unslash( (string) $wp->query_vars['rest_route'] ) ), '/' )
352 : '';
353
354 if ( 1 !== preg_match( '#^/wcpos/v([12])(?:/|$)#', $route, $matches ) ) {
355 return;
356 }
357
358 // The relay's consent callback is expected unmarked traffic (see
359 // register_public_relay_routes()), not a misconfigured client.
360 if ( '/wcpos/v1/print-jobs/relay-verification' === $route ) {
361 return;
362 }
363
364 $transient = 'wcpos_missing_request_marker_v' . $matches[1];
365 if ( false !== get_transient( $transient ) ) {
366 return;
367 }
368
369 set_transient( $transient, 1, 5 * MINUTE_IN_SECONDS );
370 Logger::warning( $route . ': request marker missing (routes still registered via namespace detection).' );
371 }
372
373 /**
374 * Adds 'wcpos' to the query variables allowed before processing.
375 *
376 * Allows (publicly allowed) query vars to be added, removed, or changed prior
377 * to executing the query. Needed to allow custom rewrite rules using your own arguments
378 * to work, or any other custom query variables you want to be publicly available.
379 *
380 * @param string[] $query_vars The array of allowed query variable names.
381 *
382 * @return string[] The array of allowed query variable names.
383 */
384 public function query_vars( array $query_vars ): array {
385 $query_vars[] = SHORT_NAME;
386
387 return $query_vars;
388 }
389
390 /**
391 * Allow HEAD checks for WP API Link URL and server uptime.
392 *
393 * This is the NON-REST lane and is not part of the REST wire contract
394 * ({@see Rest_Cors}): `send_headers` fires from `WP::main()`, which a REST
395 * request never reaches — core's `rest_api_loaded()` runs on
396 * `parse_request` and dies. What it serves is the app's site-discovery
397 * probe against an ordinary page: the app reads the `Link:
398 * <.../wp-json/>; rel="https://api.w.org/"` header cross-origin to find
399 * the REST root, which needs both headers below. Some servers turn HEAD
400 * into GET, hence the `?_method=head` query param rather than the method.
401 *
402 * This is live, not legacy. The client calls it on every Connect:
403 * `packages/core/src/screens/auth/hooks/use-url-discovery.ts` issues
404 * `http.head()` against the site root, and
405 * `packages/hooks/src/use-http-client/use-http-client.tsx` sets
406 * `params._method = 'HEAD'` on every HEAD request (both in the client
407 * monorepo). That same client code deliberately omits the `X-WCPOS`
408 * marker for HEAD, so this handler cannot be marker-gated and must stay
409 * unconditional. 521ccb9a added it; the `?wcpos=1` gate it originally
410 * carried is long gone.
411 *
412 * @return void
413 */
414 public function send_headers(): void {
415 // some server convert HEAD to GET method, so use this query param instead.
416 if ( isset( $_GET['_method'] ) && 'head' === strtolower( sanitize_text_field( wp_unslash( $_GET['_method'] ) ) ) ) {
417 header( 'Access-Control-Allow-Origin: *' );
418 header( 'Access-Control-Expose-Headers: Link' );
419 }
420 }
421
422 /**
423 * Some security plugins will set X-Frame-Options: SAMEORIGIN/DENY, which will prevent the POS desktop
424 * application from opening pages like the login in an iframe.
425 *
426 * For pages we need, we will remove the X-Frame-Options header.
427 *
428 * @param mixed $wp The WP object.
429 *
430 * @return void
431 */
432 public function remove_x_frame_options( $wp ): void {
433 if ( woocommerce_pos_request() || isset( $wp->query_vars['wcpos-login'] ) ) {
434 if ( ! headers_sent() && \function_exists( 'header_remove' ) ) {
435 header_remove( 'X-Frame-Options' );
436 }
437 }
438 }
439
440 /**
441 * Common initializations.
442 */
443 private function init_common(): void {
444 // init the Services.
445 SettingsService::instance();
446 AuthService::instance();
447 Extensions::instance();
448 Receipt_Snapshot_Store::instance();
449
450 // init other functionality needed by both frontend and admin.
451 new i18n();
452 new Gateways();
453 new Products();
454 new Orders();
455 new Emails();
456 new Templates();
457 Services\Stock_Validator::instance();
458 new Services\Decimal_Quantities();
459 new Services\Customer_Meta_Parity();
460 new Services\Print_Job_Service();
461 new Services\Cloud_Print_Trigger_Service();
462 new Services\Cloud_Print_Submit_Service();
463 new Services\Cloud_Print_Relay_Service();
464 }
465
466 /**
467 * Frontend specific initializations.
468 */
469 private function init_frontend(): void {
470 if ( ! is_admin() ) {
471 new Template_Router();
472 new Form_Handler();
473 new Storefront_Receipts();
474 }
475 }
476
477 /**
478 * Admin specific initializations.
479 */
480 private function init_admin(): void {
481 if ( is_admin() ) {
482 // Register AJAX handler before the branch so it's available during AJAX requests.
483 add_action( 'wp_ajax_wcpos_track_upgrade_click_ajax', array( Menu::class, 'handle_upgrade_click_ajax' ) );
484 add_action( 'admin_post_wcpos_track_upgrade_click', array( Menu::class, 'handle_upgrade_click_redirect' ) );
485
486 if ( wp_doing_ajax() ) {
487 new AJAX();
488 } else {
489 new Admin();
490 }
491 }
492 }
493
494 /**
495 * Integrations.
496 */
497 private function init_integrations(): void {
498 // WooCommerce Bookings - http://www.woothemes.com/products/woocommerce-bookings/
499 // if ( class_exists( 'WC-Bookings' ) ) {
500 // new Integrations\Bookings();
501 // }.
502
503 // Yoast SEO - https://wordpress.org/plugins/wordpress-seo/.
504 if ( class_exists( 'WPSEO_Options' ) ) {
505 new Integrations\WPSEO();
506 }
507
508 // wePOS alters the WooCommerce REST API, breaking the expected schema
509 // It's very bad form on their part, but we need to work around it.
510 new Integrations\WePOS();
511 }
512 }
513