PluginProbe
WCPOS – Point of Sale (POS) plugin for WooCommerce / 1.10.17
WCPOS – Point of Sale (POS) plugin for WooCommerce v1.10.17
1.10.25 1.10.24 1.10.23 1.10.22 1.10.21 1.10.20 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 All 169 releases
← All changes | includes/Init.php +292 -278 1.10.25 → 1.10.17 View file →
@@ -12,9 +12,11 @@
12 12
13 13 use WCPOS\WooCommercePOS\Admin\Consent;
14 14 use WCPOS\WooCommercePOS\Admin\Menu;
15 15 use WCPOS\WooCommercePOS\Services\Auth as AuthService;
16 -use WCPOS\WooCommercePOS\Services\Service_Groups;
16 +use WCPOS\WooCommercePOS\Services\Extensions;
17 +use WCPOS\WooCommercePOS\Services\Receipt_Snapshot_Store;
18 +use WCPOS\WooCommercePOS\Services\Settings as SettingsService;
17 19
18 20 /**
19 21 * Init class.
20 22 */
@@ -19,281 +21,204 @@
19 21 * Init class.
20 22 */
21 23 class Init {
22 24 /**
23 - * Observer awaiting the constructor's non-hook seed step.
25 + * Constructor — the plugin's entire `plugins_loaded` hook wiring.
24 26 *
25 - * @var Sync\Visibility_Observer|null
26 - */
27 - private $visibility_observer;
28 -
29 - /**
30 - * Install the ordered wiring declared by {@see hook_rows()}.
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.
31 30 *
32 - * Non-hook setup stays here, interleaved at its original registration boundaries.
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, plus `shutdown` | `Sync\Sync_Journal` (34 callbacks) | 10 (`shutdown` at `PHP_INT_MAX`) | `shutdown`: order-critical (by number) | Default throughout. `woocommerce_update_order` only MARKS the order dirty; the `hook:update` row lands on `flush_pending_order_updates()` — at `shutdown`, before any other-origin row for that order, or when a different order is saved — so one online checkout writes one update row, not eleven. The shutdown flush runs LAST because WooCommerce saves the customer at 10 and the session at 20; a save those trigger after the flush is written immediately. |
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), plus `shutdown` | `Sync\Integrity_Digest` | 10 (`shutdown` at `PHP_INT_MAX`) | 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. Every save — product, variation, customer, order — only MARKS the digest dirty; the upsert lands on `flush_pending_digests()` at `shutdown`, before any `Digest_Index::read_digests()`, or when the queue holds 50 records. |
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 + * | 26 | `rest_request_after_callbacks` | `Services\Error_Reporter::filter_rest_request_after_callbacks` | **999** | order-critical (by number) | Runs late so the response status it reports is the one the client receives. |
88 + *
89 + * ## The one pair where statement order is the whole mechanism
90 + *
91 + * Rows 20 and 23 share `determine_current_user` AND priority 20, so insertion
92 + * order — and nothing else — decides which runs first. 20 puts both after
93 + * WordPress core's own handlers, which `default-filters.php` registers before
94 + * any plugin loads: `wp_validate_auth_cookie` at 10, then
95 + * `wp_validate_logged_in_cookie` and `wp_validate_application_password`, both
96 + * at 20 and therefore both ahead of these two.
97 + *
98 + * The guard must run FIRST. It records into `pre_wcpos_user_id` whichever user
99 + * some EARLIER filter had already authenticated; a non-zero value means the
100 + * request proved itself with a cookie or application password, so
101 + * `Core_Order_Audit_Guard::is_wcpos_jwt_authenticated()` returns false and the
102 + * request keeps its normal power over order meta.
103 + *
104 + * Swap the two statements and the guard records the user WCPOS's own JWT filter
105 + * just authenticated. `pre_wcpos_user_id` is then non-zero on every
106 + * token-authenticated request, `is_wcpos_jwt_authenticated()` returns false for
107 + * all of them, and forged `_pos_*` audit meta on `/wc/v3/orders` is accepted.
108 + * It fails OPEN, silently, on a route no smoke test touches.
109 + *
110 + * Pinned by `tests/includes/Test_Init_Hook_Wiring.php`, which asserts the two
111 + * callbacks' ARRAY POSITIONS inside `callbacks[20]` — asserting priorities
112 + * would pass on the broken order.
33 113 */
34 114 public function __construct() {
115 + // global helper functions.
35 116 require_once PLUGIN_PATH . 'includes/wcpos-functions.php';
36 117 require_once PLUGIN_PATH . 'includes/wcpos-store-functions.php';
37 118 wp_cache_add_global_groups( 'wc_pos_user_uuid_locks' );
38 119
39 - $rows = $this->hook_rows( true );
40 - Hook_Manifest::validate( $rows );
41 - Hook_Manifest::install( wp_list_filter( $rows, array( 'phase' => 'pre-latch' ) ) );
42 - $sync_latched = Sync\Api::SCHEMA_VERSION === get_option( Sync\Api::SCHEMA_OPTION, null );
43 - foreach ( $rows as $row ) {
44 - if ( 'pre-latch' === $row['phase'] || ( 'sync-latched' === $row['phase'] && ! $sync_latched ) ) {
45 - continue;
46 - }
47 - if ( array( $this, 'init' ) === $row['callback'] ) {
48 - ( new Sync\Config_Fingerprint() )->maybe_cleanup_legacy_options();
49 - }
50 - Hook_Manifest::install( array( $row ) );
51 - if ( null !== $this->visibility_observer ) {
52 - $this->visibility_observer->maybe_seed_hidden_tombstones();
53 - $this->visibility_observer = null;
54 - }
120 + // Tracking consent pop-up + callout. Registered here (during
121 + // plugins_loaded) so its lifecycle hooks (activated_plugin,
122 + // upgrader_process_complete) are in place before those actions
123 + // fire on a plugin activation or update request.
124 + new Consent();
125 + add_filter( 'woocommerce_pos_rest_api_controllers', array( \WCPOS\WooCommercePOS\Sync\Api::class, 'register_controllers' ) );
126 + add_action( \WCPOS\WooCommercePOS\Sync\Integrity_Digest::REBUILD_HOOK, array( \WCPOS\WooCommercePOS\Sync\Integrity_Digest::class, 'run_scheduled_rebuild' ) );
127 + // Gate on the schema latch, not a live Health probe: the latch is only
128 + // set AFTER install verified every table (latch-after-verify), so a
129 + // per-request SHOW TABLES sweep buys nothing — and a table lost after
130 + // latching is already survivable (observer writes fail open and the
131 + // REST health gate 503s the sync endpoints).
132 + $sync_schema_latched = \WCPOS\WooCommercePOS\Sync\Api::SCHEMA_VERSION === get_option( \WCPOS\WooCommercePOS\Sync\Api::SCHEMA_OPTION, null );
133 + if ( $sync_schema_latched ) {
134 + // Normalize structured meta at priority 5, before revision stamps at 9
135 + // and UUID, digest, and variable-price stamps at priority 10. Kept out
136 + // of the augmentation pipeline because it also serves the order lane.
137 + \WCPOS\WooCommercePOS\Sync\Meta_Normalizer::register_hooks();
138 + add_filter( 'woocommerce_pos_sync_serialized_order', array( \WCPOS\WooCommercePOS\Sync\Pos_Uuid::class, 'stamp_serialized_record' ), 10, 3 );
139 + // ONE seam for both product read lanes: the batch catalog proxy and the
140 + // per-object serializer. Every stamper is declared once inside; both
141 + // public filter names stay live as projections of it. The order pull
142 + // lane's digest stamper is wired there too — it was hand-added here,
143 + // under this same latch, which made the pipeline's single-wiring-site
144 + // claim untrue.
145 + \WCPOS\WooCommercePOS\Sync\Augmentation_Pipeline::install();
55 146 }
56 - }
57 147
58 - /**
59 - * Declare bootstrap wiring in registration order, without installing it.
60 - *
61 - * Null hooks invoke registrars immediately; their internal priorities/arity stay
62 - * in register_hooks(). Phases keep the schema read after pre-latch hooks;
63 - * sync-latched rows are post-read hooks omitted when the latch is down.
64 - * The guard registrar MUST precede the JWT row: both register at priority 20,
65 - * after core cookie/application-password handlers. Reversing them attributes
66 - * JWT identity to prior authentication and fails open on /wc/v3/orders.
67 - *
68 - * @param bool $sync_latched Whether the verified sync schema latch is set.
69 - * @return array Ordered rows consumed by Hook_Manifest::install().
70 - */
71 - public function hook_rows( bool $sync_latched ): array {
72 - $rows = array(
73 - array(
74 - 'hook' => null,
75 - 'callback' => static function (): void {
76 - new Consent();
77 - },
78 - 'priority' => 10,
79 - 'args' => 0,
80 - 'reason' => 'Default 10; lifecycle hooks must exist during plugins_loaded, before activation/update actions.',
81 - 'phase' => 'pre-latch',
82 - ),
83 - array(
84 - 'hook' => 'woocommerce_pos_rest_api_controllers',
85 - 'callback' => array( Sync\Api::class, 'register_controllers' ),
86 - 'priority' => 10,
87 - 'args' => 1,
88 - 'reason' => 'Default; sole callback. Response registrars stay inside this filter to retain REST activation timing.',
89 - 'phase' => 'pre-latch',
90 - ),
91 - array(
92 - 'hook' => Sync\Integrity_Digest::REBUILD_HOOK,
93 - 'callback' => array( Sync\Integrity_Digest::class, 'run_scheduled_rebuild' ),
94 - 'priority' => 10,
95 - 'args' => 1,
96 - 'reason' => 'Default; sole callback. Unlatched so an already-scheduled rebuild still has a listener.',
97 - 'phase' => 'pre-latch',
98 - ),
99 - array(
100 - 'hook' => null,
101 - 'callback' => array( Sync\Meta_Normalizer::class, 'register_hooks' ),
102 - 'priority' => 10,
103 - 'args' => 0,
104 - 'reason' => 'Priority 5 before revision 9 and augmentation 10, so revisions match bare wc/v3 rereads; also serves orders.',
105 - 'phase' => 'sync-latched',
106 - ),
107 - array(
108 - 'hook' => 'woocommerce_pos_sync_serialized_order',
109 - 'callback' => array( Sync\Pos_Uuid::class, 'stamp_serialized_record' ),
110 - 'priority' => 10,
111 - 'args' => 3,
112 - 'reason' => 'After normalization at 5, in step with product stampers at 10.',
113 - 'phase' => 'sync-latched',
114 - ),
115 - array(
116 - 'hook' => null,
117 - 'callback' => array( Sync\Augmentation_Pipeline::class, 'install' ),
118 - 'priority' => 10,
119 - 'args' => 0,
120 - 'reason' => 'Revision 9 hashes normalized, unaugmented bytes; UUID/digest/projections at 10 preserve extension order, including order-pull digests.',
121 - 'phase' => 'sync-latched',
122 - ),
123 - array(
124 - 'hook' => null,
125 - 'callback' => array( Sync\Pos_Uuid::class, 'register_hooks' ),
126 - 'priority' => 10,
127 - 'args' => 0,
128 - 'reason' => 'Default 10; identity is unconditional: before-save UUIDs land in the same write and native restores re-prove ownership (ADR 0038).',
129 - 'phase' => 'post-latch',
130 - ),
131 - array(
132 - 'hook' => null,
133 - 'callback' => static function (): void {
134 - ( new Sync\Sync_Journal() )->register_hooks();
135 - },
136 - 'priority' => 10,
137 - 'args' => 0,
138 - 'reason' => 'Default 10; dirty order updates coalesce until shutdown at PHP_INT_MAX, after WooCommerce customer 10/session 20 saves.',
139 - 'phase' => 'sync-latched',
140 - ),
141 - array(
142 - 'hook' => null,
143 - 'callback' => function (): void {
144 - $this->visibility_observer = new Sync\Visibility_Observer();
145 - $this->visibility_observer->register_hooks();
146 - },
147 - 'priority' => 10,
148 - 'args' => 0,
149 - 'reason' => 'Default 10 after journal; records servable-set transitions, using generic pre-delete_option; Init then seeds tombstones.',
150 - 'phase' => 'sync-latched',
151 - ),
152 - array(
153 - 'hook' => null,
154 - 'callback' => static function (): void {
155 - ( new Sync\Sync_Journal_Purge() )->register_hooks();
156 - },
157 - 'priority' => 10,
158 - 'args' => 0,
159 - 'reason' => 'Default 10; sole cron listener; the registrar also schedules the daily purge.',
160 - 'phase' => 'sync-latched',
161 - ),
162 - array(
163 - 'hook' => null,
164 - 'callback' => static function (): void {
165 - ( new Sync\Integrity_Digest() )->register_hooks();
166 - },
167 - 'priority' => 10,
168 - 'args' => 0,
169 - 'reason' => 'Default 10, shutdown PHP_INT_MAX; journal registers first on shared hooks (reason unknown); dirty digests coalesce until flush.',
170 - 'phase' => 'sync-latched',
171 - ),
172 - array(
173 - 'hook' => 'init',
174 - 'callback' => array( $this, 'init' ),
175 - 'priority' => 10,
176 - 'args' => 1,
177 - 'reason' => 'Default 10; free services must exist before Pro init at 20.',
178 - 'phase' => 'post-latch',
179 - ),
180 - array(
181 - 'hook' => 'rest_api_init',
182 - 'callback' => array( $this, 'init_rest_api' ),
183 - 'priority' => 20,
184 - 'args' => 1,
185 - 'reason' => 'Original reason unknown (8f2b9eac); Pro deliberately registers before free at 9.',
186 - 'phase' => 'post-latch',
187 - ),
188 - array(
189 - 'hook' => 'query_vars',
190 - 'callback' => array( $this, 'query_vars' ),
191 - 'priority' => 10,
192 - 'args' => 1,
193 - 'reason' => 'Default; appends one variable.',
194 - 'phase' => 'post-latch',
195 - ),
196 - array(
197 - 'hook' => 'pre_update_option_woocommerce_pos_pro_settings_license',
198 - 'callback' => array( self::class, 'remove_license_transient' ),
199 - 'priority' => 10,
200 - 'args' => 2,
201 - 'reason' => 'Default; the reentrancy guard, not priority, makes legacy Pro license cache invalidation safe (f33b8d655).',
202 - 'phase' => 'post-latch',
203 - ),
204 - array(
205 - 'hook' => null,
206 - 'callback' => array( Rest_Cors::class, 'register_hooks' ),
207 - 'priority' => 10,
208 - 'args' => 0,
209 - 'reason' => 'Unconditional for unmarked preflights/relay; serve at 20 after core CORS at 10 so WCPOS is the last writer.',
210 - 'phase' => 'post-latch',
211 - ),
212 - array(
213 - 'hook' => 'send_headers',
214 - 'callback' => array( $this, 'send_headers' ),
215 - 'priority' => 99,
216 - 'args' => 1,
217 - 'reason' => 'Unknown beyond running late for WPSEO integration (62da70551).',
218 - 'phase' => 'post-latch',
219 - ),
220 - array(
221 - 'hook' => 'send_headers',
222 - 'callback' => array( $this, 'remove_x_frame_options' ),
223 - 'priority' => 9999,
224 - 'args' => 1,
225 - 'reason' => 'Must remove X-Frame-Options AFTER security plugins set it (80ee545a5).',
226 - 'phase' => 'post-latch',
227 - ),
228 - array(
229 - 'hook' => null,
230 - 'callback' => static function (): void {
231 - ( new Services\Core_Order_Audit_Guard() )->register_hooks();
232 - },
233 - 'priority' => 10,
234 - 'args' => 0,
235 - 'reason' => 'Auth provenance at 20 MUST register before JWT at 20, after core cookie/password auth; rest_pre_dispatch reads it at 10.',
236 - 'phase' => 'post-latch',
237 - ),
238 - array(
239 - 'hook' => null,
240 - 'callback' => array( Sync\Coupon_Modified_Date::class, 'register_hooks' ),
241 - 'priority' => 10,
242 - 'args' => 0,
243 - 'reason' => 'Default 10; unconditional meta-only coupon edit timestamps for date-based replication; journal uses wall clock, not post_modified.',
244 - 'phase' => 'post-latch',
245 - ),
246 - array(
247 - 'hook' => 'determine_current_user',
248 - 'callback' => array( $this, 'determine_current_user_early' ),
249 - 'priority' => 20,
250 - 'args' => 1,
251 - 'reason' => 'At 20 AFTER the audit guard and core cookie/password handlers; register before init, regardless of the request marker.',
252 - 'phase' => 'post-latch',
253 - ),
254 - array(
255 - 'hook' => null,
256 - 'callback' => static function (): void {
257 - ( new Services\Lifecycle_Events() )->register_hooks();
258 - },
259 - 'priority' => 10,
260 - 'args' => 0,
261 - 'reason' => 'Default 10; append after auth pair; admin_init flushes pending events and consent-gates refresh scheduling, not the cron listener.',
262 - 'phase' => 'post-latch',
263 - ),
264 - array(
265 - 'hook' => null,
266 - 'callback' => static function (): void {
267 - Services\Error_Reporter::instance()->register_hooks();
268 - },
269 - 'priority' => 10,
270 - 'args' => 0,
271 - 'reason' => 'Append after lifecycle; REST priority 999 reports the final response status, gated by consent (#1811).',
272 - 'phase' => 'post-latch',
273 - ),
274 - array(
275 - 'hook' => null,
276 - 'callback' => static function (): void {
277 - add_action( 'wp_logout', array( Services\Auth::class, 'revoke_web_session_on_logout' ), 10, 1 );
278 - add_action( 'password_reset', array( Services\Auth::class, 'revoke_sessions_on_password_reset' ), 10, 1 );
279 - add_action( 'profile_update', array( Services\Auth::class, 'revoke_sessions_on_password_change' ), 10, 2 );
280 - },
281 - 'priority' => 10,
282 - 'args' => 0,
283 - 'reason' => 'Default 10; logout ends this browser\'s web POS session, a password reset or change ends every POS session. Auth is built only when one fires.',
284 - 'phase' => 'post-latch',
285 - ),
286 - );
148 + // Identity is core, not an observer benchmark variable: every product is
149 + // born with a UUID even before the schema latch is healthy. The before-save
150 + // hook writes it in the same save.
151 + \WCPOS\WooCommercePOS\Sync\Pos_Uuid::register_hooks();
287 152
288 - return array_values(
289 - array_filter(
290 - $rows,
291 - static function ( array $row ) use ( $sync_latched ): bool {
292 - return $sync_latched || 'sync-latched' !== $row['phase'];
293 - }
294 - )
295 - );
153 + if ( $sync_schema_latched ) {
154 + ( new \WCPOS\WooCommercePOS\Sync\Sync_Journal() )->register_hooks();
155 + $visibility_observer = new \WCPOS\WooCommercePOS\Sync\Visibility_Observer();
156 + $visibility_observer->register_hooks();
157 + $visibility_observer->maybe_seed_hidden_tombstones();
158 + ( new \WCPOS\WooCommercePOS\Sync\Sync_Journal_Purge() )->register_hooks();
159 + ( new \WCPOS\WooCommercePOS\Sync\Integrity_Digest() )->register_hooks();
160 + }
161 +
162 + ( new \WCPOS\WooCommercePOS\Sync\Config_Fingerprint() )->maybe_cleanup_legacy_options();
163 +
164 + // Init hooks.
165 + add_action( 'init', array( $this, 'init' ) );
166 + add_action( 'rest_api_init', array( $this, 'init_rest_api' ), 20 );
167 + add_filter( 'query_vars', array( $this, 'query_vars' ) );
168 +
169 + // Remove this once Pro settings have been moved to the new settings service.
170 + add_filter( 'pre_update_option_woocommerce_pos_pro_settings_license', array( self::class, 'remove_license_transient' ), 10, 2 );
171 +
172 + // The REST wire contract — CORS and shared-cache defeat — has a single
173 + // owner. Registered unconditionally, from here rather than from the
174 + // X-WCPOS-gated API class, because preflights carry no marker and the
175 + // relay's consent route is served without constructing API.
176 + Rest_Cors::register_hooks();
177 +
178 + // Non-REST API discoverability: the HEAD probe against the homepage.
179 + add_action( 'send_headers', array( $this, 'send_headers' ), 99, 1 );
180 + add_action( 'send_headers', array( $this, 'remove_x_frame_options' ), 9999, 1 );
181 +
182 + /*
183 + * Add the global JWT authentication filter and its core-route audit guard.
184 + *
185 + * Hook order: plugins_loaded -> init (determine_current_user) -> rest_api_init
186 + *
187 + * This filter runs at priority 20, after WordPress core's cookie auth handlers.
188 + * It must be registered here (during plugins_loaded) because determine_current_user
189 + * fires during 'init', which is BEFORE rest_api_init where our API class loads.
190 + * Because it authenticates WCPOS Bearer tokens on EVERY
191 + * REST request (marked or not), the audit-meta guard for core routes
192 + * must be registered just as unconditionally — never from the
193 + * X-WCPOS-gated API class, whose marker an attacker simply omits.
194 + * Registering it first lets its priority-20 provenance filter run after
195 + * core's cookie handlers but before WCPOS's JWT filter.
196 + */
197 + ( new Services\Core_Order_Audit_Guard() )->register_hooks();
198 +
199 + // Coupon post-date touch. Unconditional and lane-agnostic on purpose: a
200 + // meta-only coupon edit (amount, discount_type, usage limits) never moves
201 + // post_modified, and the client's catalogue replication is date-based
202 + // (?modified_after, filtered by WooCommerce on post_modified_gmt), so an
203 + // untouched coupon is invisible to every other till. That is true whether
204 + // the edit came from the POS, wp-admin, WP-CLI or another plugin — so this
205 + // sits outside the schema latch above because it does not use the v2 sync
206 + // tables.
207 + \WCPOS\WooCommercePOS\Sync\Coupon_Modified_Date::register_hooks();
208 +
209 + add_filter( 'determine_current_user', array( $this, 'determine_current_user_early' ), 20 );
210 +
211 + // Install lifecycle reporting. Registered last: it adds no filter that
212 + // anything else orders against, and appending keeps the ordering table
213 + // above in statement order. Deliberately NOT before the pair above —
214 + // rows 20 and 23 are decided by insertion order alone.
215 + ( new Services\Lifecycle_Events() )->register_hooks();
216 +
217 + // Consent-gated Sentry error reporting (issue #1811). Registered last for
218 + // the same reason as Lifecycle_Events: nothing orders against it. Its REST
219 + // filter runs at 999 so the status it reports is the one the client receives.
220 + Services\Error_Reporter::instance()->register_hooks();
296 221 }
297 222
298 223 /**
299 224 * Clear cached data that depends on the Pro license.
@@ -518,52 +443,141 @@
518 443 }
519 444 }
520 445
521 446 /**
447 + * Groups constructed so far in this request (test seam; see constructed_groups()).
448 + *
449 + * @var array<string, bool>
450 + */
451 + private static array $constructed = array();
452 +
453 + /**
522 454 * Common initializations, by request lane.
523 455 *
524 - * Every request gets the always group; everything else is constructed only
525 - * on the lanes that use it, and the order group additionally on the first
526 - * order write of ANY request, so the lane classifier is an optimisation
527 - * rather than a correctness gate. {@see Service_Groups} holds the membership
528 - * of each group and the reasons behind it.
456 + * Every request gets the services whose hooks WooCommerce consults on a
457 + * plain shopper page BEFORE any order exists: translations, the product
458 + * visibility filters, the order statuses and the read-side order filters
459 + * (My Account renders POS orders), the gateway registration (WooCommerce
460 + * builds its gateway list on cart pages) and the reserved-stock filter
461 + * (POS drafts must reduce online availability at add-to-cart time).
529 462 *
530 - * Measured 2026-09-03: a storefront page loaded ~80 plugin files and 22
531 - * objects for hooks that never fire there (see
532 - * .claude/research/2026-09-03-lazy-service-construction-spec.md).
463 + * Everything else is constructed only on the lanes that use it, and the
464 + * order-event services additionally on the first order write of ANY request
465 + * ({@see ensure_order_services()}), so the lane classifier is an
466 + * optimisation rather than a correctness gate. Measured 2026-09-03: a
467 + * storefront page loaded ~80 plugin files and 22 objects for hooks that
468 + * never fire there (see .claude/research/2026-09-03-lazy-service-construction-spec.md).
533 469 */
534 470 private function init_common(): void {
535 - Service_Groups::ensure( Service_Groups::ALWAYS );
471 + self::$constructed['always'] = true;
536 472
473 + // init the Services.
474 + SettingsService::instance();
475 + AuthService::instance();
476 +
477 + // Needed on every lane, including a plain storefront page.
478 + new i18n();
479 + new Gateways();
480 + new Products();
481 + new Orders();
482 + Services\Stock_Validator::instance();
483 +
537 484 if ( Services\Request_Lane::is_storefront() ) {
538 485 // Order-event services arrive on the first order write, if any.
539 - Service_Groups::arm_order_group();
486 + self::arm_order_services();
540 487 return;
541 488 }
542 489
543 - Service_Groups::ensure( Service_Groups::ORDER );
544 - Service_Groups::ensure( Service_Groups::POS );
490 + self::ensure_order_services();
491 + self::construct_pos_services();
545 492 }
546 493
547 494 /**
495 + * Services only POS, admin, REST, cron and CLI requests use.
496 + */
497 + private static function construct_pos_services(): void {
498 + if ( isset( self::$constructed['pos'] ) ) {
499 + return;
500 + }
501 + self::$constructed['pos'] = true;
502 + Extensions::instance();
503 + new Services\Decimal_Quantities();
504 + new Services\Customer_Meta_Parity();
505 + }
506 +
507 + /**
508 + * Hook the order-event services to the first order write of the request.
509 + *
510 + * Every WooCommerce order write — create, update, status transition,
511 + * `payment_complete()`, refund — goes through `WC_Abstract_Order::save()`,
512 + * which fires `woocommerce_before_order_object_save` before the data store
513 + * writes and before `woocommerce_new_order` / `woocommerce_order_status_changed`
514 + * / `woocommerce_payment_complete` fire. Priority 0 there means every
515 + * observer exists before any order is written — on a webhook, a cron
516 + * spawned from a page view, a third-party plugin creating an order on
517 + * `template_redirect`, or a lane the classifier got wrong. Nothing in the
518 + * order group listens to trash or delete, so those need no arming.
519 + */
520 + private static function arm_order_services(): void {
521 + add_action( 'woocommerce_before_order_object_save', array( self::class, 'ensure_order_services' ), 0, 0 );
522 + }
523 +
524 + /**
548 525 * Construct the order-event services exactly once per request.
549 526 *
550 527 * Idempotent and safe to call after `init`; each service handles its own
551 528 * late registration. Fires `woocommerce_pos_order_services_ready` once so
552 529 * Pro and extensions can construct their own order-event services at the
553 - * same moment on every lane. Implementation now lives in Service_Groups.
530 + * same moment on every lane.
554 531 */
555 532 public static function ensure_order_services(): void {
556 - Service_Groups::ensure( Service_Groups::ORDER );
533 + if ( isset( self::$constructed['order'] ) ) {
534 + return;
535 + }
536 + self::$constructed['order'] = true;
537 +
538 + Receipt_Snapshot_Store::instance();
539 + new Emails();
540 + new Templates();
541 + new Services\Print_Job_Service();
542 + new Services\Cloud_Print_Trigger_Service();
543 + new Services\Cloud_Print_Submit_Service();
544 + new Services\Cloud_Print_Relay_Service();
545 +
546 + /**
547 + * Fires once per request when the POS order-event services exist:
548 + * eagerly on POS, admin, REST, cron and CLI requests (from this
549 + * plugin's `init` callback at priority 10), and on a storefront
550 + * request the moment the first order is about to be written.
551 + *
552 + * Because the eager firing happens at `init` priority 10, a listener
553 + * added later than that (for example from another plugin's `init`
554 + * callback at priority 20) must check `did_action()` first and
555 + * construct immediately when the action has already fired.
556 + *
557 + * @since 1.10.8
558 + */
559 + do_action( 'woocommerce_pos_order_services_ready' );
557 560 }
558 561
559 562 /**
563 + * Which service groups this request has constructed: 'always', 'order', 'pos'.
564 + *
565 + * @internal Test seam.
566 + *
567 + * @return string[]
568 + */
569 + public static function constructed_groups(): array {
570 + return array_keys( self::$constructed );
571 + }
572 +
573 + /**
560 574 * Forget which groups were constructed. Tests only.
561 575 *
562 576 * @internal
563 577 */
564 578 public static function reset_request_state(): void {
565 - Service_Groups::reset();
579 + self::$constructed = array();
566 580 Services\Request_Lane::reset();
567 581 }
568 582
569 583 /**