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

Digest_Index.php in WCPOS – Point of Sale (POS) plugin for WooCommerce 1.10.0, at includes/Sync/Digest_Index.php

883 lines 38.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * WCPOS sync store component.
4 *
5 * @package WCPOS\WooCommercePOS\Sync
6 */
7
8 namespace WCPOS\WooCommercePOS\Sync;
9
10 use WCPOS\WooCommercePOS\Services\Barcode_Field;
11
12 // phpcs:disable Squiz.Commenting, Generic.Commenting -- Ported lab documentation is preserved verbatim.
13 // phpcs:disable WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Queries use internal table names and generated SQL fragments.
14
15 /**
16 * The READ half of the integrity-digest store — the sync engine's query object.
17 *
18 * {@see Integrity_Digest} owns the WRITE half (hook-time upserts, deletes and the
19 * rebuild); this class owns every question the read surface asks of the digest
20 * store, and the canonical SQL both halves share. Callers name a COLLECTION, a
21 * bucket RANGE and (optionally) FILTERS — never a table, a column or a JOIN.
22 *
23 * Three questions, one per REST consumer:
24 *
25 * - {@see bucket_aggregates} — stored-vs-current BIT_XOR per id-range bucket (the scan).
26 * - {@see bucket_drift} — the per-id mismatches inside ONE bucket (the drill-down).
27 * - {@see bucket_listing} — the authoritative live {id, digest, object_type} for one bucket.
28 *
29 * Plus the two scoping questions the same id-space owns:
30 * {@see published_product_ids} (the readable-catalog filter, one home for a rule
31 * that used to be re-spelled in every consumer) and {@see needs_product_rebuild}.
32 *
33 * Servable scoping — publish state and POS visibility — lives HERE rather than in
34 * the controllers, so "what the POS may see" is answered identically wherever the
35 * digest store is read. Visibility comes from {@see Pos_Visibility}, unchanged.
36 */
37 final class Digest_Index {
38
39 /**
40 * Legacy baseline of postmeta keys covered by the product/variation digest. Must include every key the
41 * sql-bypass fixture mutates (_price and _regular_price today — see
42 * class-fixtures-controller.php sql_bypass()) plus the keys a
43 * hook-bypassing import/inventory tool plausibly touches.
44 */
45 public const DIGESTED_META_KEYS = array( '_global_unique_id', '_price', '_regular_price', '_sale_price', '_sku', '_stock', '_stock_status' );
46
47 /**
48 * Option recording the key set the STORED digests were computed from.
49 * Never autoloaded — read only on the scan path. See {@see digest_formula_fingerprint}.
50 */
51 public const FORMULA_FP_OPTION = 'wcpos_integrity_digest_formula_fp';
52
53 /**
54 * Customer usermeta folded into the digest (ADR 0015, Leg-3 phase 7). Kept small + stable —
55 * identity/existence fields the POS keys on, NOT every usermeta row (a churny meta bloats the digest
56 * with irrelevant drift). The customer's core columns (email, display name, registered) come from
57 * wp_users directly; these four are the identifying usermeta. The site-prefixed `capabilities`
58 * meta joins them at runtime in {@see customer_digest_select_sql} (the prefix is per-site, so it
59 * cannot live in a const): roles are part of the served record under #1379, and a hookless
60 * capabilities write (direct update_user_meta/SQL/import) must drift the digest so the
61 * integrity scan can repair the stale role — no role/profile hook fires for those writes.
62 */
63 public const CUSTOMER_DIGESTED_META_KEYS = array( 'first_name', 'last_name', 'billing_email', 'billing_phone' );
64
65 /**
66 * Order postmeta folded into the digest under the CPT (legacy) storage path (ADR 0015, Leg-3 phase 7).
67 * Under HPOS these live as wc_orders COLUMNS (total_amount, customer_id) so no meta join is needed;
68 * this allowlist only applies to the wp_posts fallback. Kept minimal — existence/identity signal.
69 */
70 public const ORDER_DIGESTED_META_KEYS = array( '_order_total', '_customer_user' );
71
72 /**
73 * The digest object_types sharing the wp_posts (product-space) id range.
74 */
75 public const OBJECT_TYPES_SQL = "('product','variation')";
76
77 private const PRODUCT_POST_TYPES_SQL = "('product','product_variation')";
78 private const EXCLUDED_POST_STATUSES_SQL = "('trash','auto-draft')";
79
80 /**
81 * Request-level memo for {@see digested_meta_keys}, KEYED BY BLOG ID. The hook write path
82 * recomputes the digest on every product save, and the barcode key costs an option read to
83 * resolve, so the set is resolved once per blog per request. Deliberately NOT invalidated
84 * when the setting changes mid-request: every digest written during one request must use
85 * ONE key set, or the stored side of a single request disagrees with itself.
86 *
87 * The blog-id key is load-bearing on multisite (the plugin network-activates). `barcode_field`
88 * is a per-site option and `Abstract_Section::read()` re-reads it uncached, so the SETTING
89 * follows switch_to_blog() correctly — a process-wide memo would not, and a batch that walks
90 * sites would then digest site B's products under site A's barcode key: the stored side would
91 * silently cover the wrong meta key, which is the exact staleness this class exists to catch.
92 *
93 * @var array<int, string[]>
94 */
95 private static array $memoized_digested_meta_keys = array();
96
97 /**
98 * The postmeta keys the product/variation digest ACTUALLY covers: the legacy baseline plus
99 * the site's configured WCPOS barcode key (mono#1234).
100 *
101 * The barcode field is merchant-configurable to any meta key, and only `_sku` /
102 * `_global_unique_id` are baseline keys. A custom carrier key was therefore undigested:
103 * a hookless write to it (importer, direct SQL, inventory tool) produced no journal row
104 * and no digest mismatch, so a till's barcodes went stale INDEFINITELY — the one field
105 * cashiers key on. Folding the configured key in closes that at tier-2 latency.
106 *
107 * Sorted so the set has ONE spelling, which is what makes
108 * {@see digest_formula_fingerprint} stable across requests.
109 *
110 * @return string[]
111 */
112 public static function digested_meta_keys(): array {
113 $blog_id = get_current_blog_id();
114 if ( ! isset( self::$memoized_digested_meta_keys[ $blog_id ] ) ) {
115 $keys = array_values( array_unique( array_merge( self::DIGESTED_META_KEYS, array( Barcode_Field::meta_key() ) ) ) );
116 sort( $keys );
117 self::$memoized_digested_meta_keys[ $blog_id ] = $keys;
118 }
119
120 return self::$memoized_digested_meta_keys[ $blog_id ];
121 }
122
123 /**
124 * Fingerprint of the key set the digest formula currently uses.
125 *
126 * Stored and live digests are only comparable when BOTH were computed from the same key
127 * set. Change the set without rebuilding and every stored digest is an old-formula value:
128 * every bucket mismatches at once and the merchant sees a store-wide false "N records need
129 * attention" for data that is already correct. So the set that produced the stored digests
130 * is recorded (by {@see \WCPOS\WooCommercePOS\Sync\Integrity_Digest::rebuild}) and
131 * compared on scan.
132 */
133 public static function digest_formula_fingerprint(): string {
134 return md5( implode( ',', self::digested_meta_keys() ) );
135 }
136
137 /**
138 * Fingerprint of the BARE baseline — the formula every install used before mono#1234.
139 *
140 * The upgrade path must not flood. Installs upgrading into this code have no recorded
141 * fingerprint, and assuming the worst would schedule a rebuild on every store. A default
142 * store (barcode = `_sku` or `_global_unique_id`, both already baseline keys) has an
143 * unchanged set, so seeding the missing option with THIS value rebuilds only the stores
144 * whose formula genuinely moved: the custom-carrier ones.
145 */
146 public static function legacy_formula_fingerprint(): string {
147 $keys = self::DIGESTED_META_KEYS;
148 sort( $keys );
149
150 return md5( implode( ',', $keys ) );
151 }
152
153 /**
154 * The POS servable-set contract (ADR 0014 WP-M5). Injectable for tests; the
155 * default instance reads the live visibility option.
156 */
157 private Pos_Visibility $visibility;
158
159 public function __construct( ?Pos_Visibility $visibility = null ) {
160 $this->visibility = $visibility ?? new Pos_Visibility();
161 }
162
163 public function table_name(): string {
164 global $wpdb;
165
166 return $wpdb->prefix . Health::STORED_DIGEST_TABLE;
167 }
168
169 /**
170 * Raise the session `group_concat_max_len` before ANY query built on {@see row_digest_select_sql}.
171 * That expression GROUP_CONCATs the digested meta; MySQL's default (1024 bytes) SILENTLY TRUNCATES
172 * for a row with many/large meta. And because the consumers (hook upsert, rebuild, scan,
173 * drill-down, bucket listing) MUST produce byte-identical digests, a truncation on one path but not
174 * another is a PERMANENT false-drift bug — the bucket never converges. So raise it identically
175 * everywhere the expression runs.
176 */
177 public function raise_group_concat_max_len(): void {
178 global $wpdb;
179 $wpdb->query( 'SET SESSION group_concat_max_len = 1048576' );
180 }
181
182 /**
183 * Canonical per-row digest SELECT, shared verbatim by the hook upsert,
184 * the scan's current-side aggregate, the drill-down and the rebuild —
185 * the stored-vs-current comparison is only sound when every consumer
186 * computes the digest with the byte-identical expression.
187 *
188 * 64-bit digest — CAST(CONV(SUBSTRING(MD5(CONCAT_WS('|', ...)),1,16),16,10) AS UNSIGNED) — over the wp_posts content columns plus
189 * the {@see digested_meta_keys} rows (key=value pairs ordered by meta_key then
190 * meta_id, so duplicate meta rows digest deterministically). Every
191 * nullable operand is COALESCE'd because CONCAT_WS silently SKIPS NULL
192 * arguments — ('a', NULL, 'b') would collide with ('a', 'b', '') —
193 * while COALESCE keeps every position present and deterministic.
194 *
195 * $where_sql may reference alias p and contain placeholders; callers
196 * run the final statement through $wpdb->prepare.
197 *
198 * @internal Engine-internal: the digest expression, not a read-surface contract.
199 */
200 public function row_digest_select_sql( string $where_sql = '' ): string {
201 global $wpdb;
202 // esc_sql because one of these keys is merchant-settable free text: the
203 // `barcode_field` setting's REST validator accepts any string, so an
204 // apostrophe would otherwise terminate the IN list — breaking EVERY digest
205 // query (hook upsert and scan alike) and taking the integrity backstop down
206 // with it. The baseline keys are literals; the barcode key is not.
207 $meta_keys_sql = "('" . implode( "','", array_map( 'esc_sql', self::digested_meta_keys() ) ) . "')";
208
209 return 'SELECT p.ID AS id,'
210 . " CASE WHEN p.post_type = 'product_variation' THEN 'variation' ELSE 'product' END AS object_type,"
211 . " CAST(CONV(SUBSTRING(MD5(CONCAT_WS('|',"
212 . ' p.ID,'
213 . " COALESCE(p.post_title,''),"
214 . " COALESCE(p.post_excerpt,''),"
215 . " COALESCE(p.post_content,''),"
216 . " COALESCE(p.post_status,''),"
217 . ' COALESCE(p.post_parent,0),'
218 . ' COALESCE(p.menu_order,0),'
219 . " COALESCE(p.post_modified_gmt,''),"
220 . " COALESCE(GROUP_CONCAT(CONCAT(pm.meta_key,'=',COALESCE(pm.meta_value,'')) ORDER BY pm.meta_key ASC, pm.meta_id ASC SEPARATOR '|'),'')"
221 // 64-bit digest (ADR 0014 M1): the top 16 hex of MD5 → an integer that still folds under
222 // BIT_XOR and fits the BIGINT UNSIGNED column, dropping the CRC32 collision floor from
223 // 2^-32 to 2^-64 (a stable per-bucket false "in sync" is unacceptable in a convergence
224 // backstop, and CRC32 is linear so structured bulk edits correlate collisions).
225 . ')),1,16),16,10) AS UNSIGNED) AS crc'
226 . " FROM {$wpdb->posts} p"
227 . " LEFT JOIN {$wpdb->postmeta} pm ON pm.post_id = p.ID AND pm.meta_key IN {$meta_keys_sql}"
228 . ' WHERE p.post_type IN ' . self::PRODUCT_POST_TYPES_SQL
229 . ' AND p.post_status NOT IN ' . self::EXCLUDED_POST_STATUSES_SQL
230 . ( '' === $where_sql ? '' : ' AND ' . $where_sql )
231 . ' GROUP BY p.ID';
232 }
233
234 /**
235 * Canonical per-CUSTOMER digest SELECT (ADR 0015, Leg-3 phase 7) — the wp_users analogue of
236 * {@see row_digest_select_sql}. Same 64-bit MD5-derived formula (BIT_XOR-foldable), over a customer's
237 * identity columns + the allowlisted usermeta. ALL wp_users rows are POS customers under #1379
238 * (1.9 parity). `$where_sql` narrows to a single user for the hook upsert (`u.ID = %d`);
239 * empty selects every user.
240 *
241 * @internal Engine-internal: the digest expression, not a read-surface contract.
242 */
243 public function customer_digest_select_sql( string $where_sql = '' ): string {
244 global $wpdb;
245 $meta_keys_sql = "('" . implode( "','", array_merge( self::CUSTOMER_DIGESTED_META_KEYS, array( $wpdb->prefix . 'capabilities' ) ) ) . "')";
246
247 return 'SELECT u.ID AS id,'
248 . " 'customer' AS object_type,"
249 . " CAST(CONV(SUBSTRING(MD5(CONCAT_WS('|',"
250 . ' u.ID,'
251 . " COALESCE(u.user_email,''),"
252 . " COALESCE(u.display_name,''),"
253 . " COALESCE(u.user_registered,''),"
254 . " COALESCE(GROUP_CONCAT(CONCAT(um.meta_key,'=',COALESCE(um.meta_value,'')) ORDER BY um.meta_key ASC, um.umeta_id ASC SEPARATOR '|'),'')"
255 // 64-bit digest (ADR 0014 M1): top 16 hex of MD5 → BIGINT UNSIGNED, folds under BIT_XOR.
256 . ')),1,16),16,10) AS UNSIGNED) AS crc'
257 . " FROM {$wpdb->users} u"
258 . " LEFT JOIN {$wpdb->usermeta} um ON um.user_id = u.ID AND um.meta_key IN {$meta_keys_sql}"
259 . ( '' === $where_sql ? '' : ' WHERE ' . $where_sql )
260 . ' GROUP BY u.ID';
261 }
262
263 /**
264 * Canonical per-ORDER digest SELECT (ADR 0015, Leg-3 phase 7) — HPOS/CPT-aware. Under HPOS orders live
265 * in WooCommerce's own {prefix}wc_orders table (status/total/customer are COLUMNS); under legacy CPT
266 * they're wp_posts + postmeta. Per install exactly ONE path runs (an install is HPOS or CPT, never both),
267 * so stored-vs-current always uses the same path — self-consistent. Same 64-bit formula.
268 *
269 * `$id_condition` narrows to a single order / a bucket range using the neutral `{id}` placeholder,
270 * substituted with the path's real id column (o.id HPOS, p.ID CPT) so callers stay path-agnostic.
271 *
272 * LIVE-VERIFY: the HPOS column set is shape-asserted here (fake wpdb); verify against a real HPOS store.
273 *
274 * @internal Engine-internal: the digest expression, not a read-surface contract.
275 */
276 public function order_digest_select_sql( string $id_condition = '' ): string {
277 global $wpdb;
278 $hpos = $this->orders_are_hpos();
279 $id_col = $hpos ? 'o.id' : 'p.ID';
280 $condition = '' === $id_condition ? '' : ' AND ' . str_replace( '{id}', $id_col, $id_condition );
281
282 if ( $hpos ) {
283 $orders_table = $wpdb->prefix . 'wc_orders';
284 return 'SELECT o.id AS id,'
285 . " 'order' AS object_type,"
286 . " CAST(CONV(SUBSTRING(MD5(CONCAT_WS('|',"
287 . ' o.id,'
288 . " COALESCE(o.status,''),"
289 . " COALESCE(o.type,''),"
290 . " COALESCE(o.total_amount,''),"
291 . ' COALESCE(o.customer_id,0),'
292 . " COALESCE(o.date_updated_gmt,''))),1,16),16,10) AS UNSIGNED) AS crc"
293 . " FROM {$orders_table} o"
294 . " WHERE o.type = 'shop_order' AND o.status NOT IN ('trash','auto-draft')"
295 . $condition;
296 }
297
298 $meta_keys_sql = "('" . implode( "','", self::ORDER_DIGESTED_META_KEYS ) . "')";
299 return 'SELECT p.ID AS id,'
300 . " 'order' AS object_type,"
301 . " CAST(CONV(SUBSTRING(MD5(CONCAT_WS('|',"
302 . ' p.ID,'
303 . " COALESCE(p.post_status,''),"
304 . " COALESCE(p.post_modified_gmt,''),"
305 . " COALESCE(GROUP_CONCAT(CONCAT(pm.meta_key,'=',COALESCE(pm.meta_value,'')) ORDER BY pm.meta_key ASC, pm.meta_id ASC SEPARATOR '|'),''))),1,16),16,10) AS UNSIGNED) AS crc"
306 . " FROM {$wpdb->posts} p"
307 . " LEFT JOIN {$wpdb->postmeta} pm ON pm.post_id = p.ID AND pm.meta_key IN {$meta_keys_sql}"
308 . " WHERE p.post_type = 'shop_order' AND p.post_status NOT IN " . self::EXCLUDED_POST_STATUSES_SQL
309 . $condition
310 . ' GROUP BY p.ID';
311 }
312
313 /**
314 * Bulk-read the STORED 64-bit digests for ONE collection's id-space -> `[id => digest string]`.
315 *
316 * ONE reader for every id-space. The registry row names the object types the
317 * collection stores (products carries product+variation; customers and orders
318 * carry their own), so no id-space can bleed into another's reconcile and a
319 * fourth id-space needs no fourth body. A collection with no digest group reads
320 * nothing rather than falling through to the products digests.
321 *
322 * The digest is BIGINT UNSIGNED (above PHP_INT_MAX), so it is returned as a
323 * STRING (ADR 0014 M1). Ids with no stored digest yet (never hooked/rebuilt) are
324 * simply absent from the result.
325 *
326 * @param string $collection Canonical plural collection name.
327 * @param int[] $ids Requested ids in the collection's own id-space.
328 *
329 * @return array<int, string>
330 */
331 public function read_digests( string $collection, array $ids ): array {
332 global $wpdb;
333 $object_types = self::digest_object_types( $collection );
334 if ( array() === $object_types ) {
335 return array();
336 }
337 $ids = array_values(
338 array_unique(
339 array_filter(
340 array_map( 'intval', $ids ),
341 static function ( $id ) {
342 return $id > 0;
343 }
344 )
345 )
346 );
347 if ( array() === $ids ) {
348 return array();
349 }
350 $placeholders = implode( ',', array_fill( 0, \count( $ids ), '%d' ) );
351 $rows = $wpdb->get_results(
352 $wpdb->prepare(
353 'SELECT object_id, digest FROM ' . $this->table_name()
354 . ' WHERE ' . self::object_type_predicate_sql( $object_types )
355 . ' AND object_id IN (' . $placeholders . ')',
356 ...$ids
357 ),
358 ARRAY_A
359 );
360 $out = array();
361 foreach ( (array) $rows as $row ) {
362 $out[ (int) $row['object_id'] ] = (string) $row['digest'];
363 }
364
365 return $out;
366 }
367
368 /**
369 * Narrow a collection's ids to what this store will still serve — the digest
370 * endpoint's authoritative-absence answer.
371 *
372 * FAIL-OPEN, deliberately: on ANY SQL error every requested id comes back
373 * servable. The caller turns an UNservable id into `deleted: true` and the till
374 * acts on that by dropping its local record — for orders, order data — so a
375 * database hiccup must never be able to manufacture a deletion. The same rule
376 * covers a collection this store cannot answer for at all.
377 *
378 * @param string $collection Canonical plural collection name.
379 * @param int[] $ids Requested ids in request order.
380 *
381 * @return int[] Servable ids in request order.
382 */
383 public function servable( string $collection, array $ids ): array {
384 global $wpdb;
385 $ids = array_values( array_map( 'intval', $ids ) );
386 if ( array() === $ids ) {
387 return array();
388 }
389 $row = Collections::row( $collection );
390 $live_rows = isset( $row['digest']['live_rows'] ) ? (string) $row['digest']['live_rows'] : '';
391 // Products are the one collection whose servability is NARROWER than a live
392 // row: POS visibility and the readable-catalog scope both apply, so the
393 // richer reader owns them. Every other id-space is exactly its live row.
394 $products = 'products' === $collection;
395 if ( ! $products && ( '' === $live_rows || ! method_exists( $this, $live_rows ) ) ) {
396 return $ids;
397 }
398 $wpdb->last_error = '';
399 if ( $products ) {
400 $servable_ids = $this->servable_product_ids( $ids, true );
401 } else {
402 $predicate = (string) \call_user_func( array( $this, $live_rows ), 'requested.id' );
403 $requested = implode( ' UNION ALL ', array_fill( 0, \count( $ids ), 'SELECT %d AS id' ) );
404 $servable_ids = $wpdb->get_col(
405 $wpdb->prepare(
406 'SELECT requested.id FROM (' . $requested . ') requested WHERE ' . $predicate,
407 ...$ids
408 )
409 );
410 }
411 /** @var string $last_error */
412 $last_error = $wpdb->last_error;
413
414 return '' !== $last_error
415 ? $ids
416 : array_values( array_intersect( $ids, array_map( 'intval', (array) $servable_ids ) ) );
417 }
418
419 /**
420 * The registry's digest object types for a collection; empty when the collection
421 * owns no digest id-space (fail closed — never a fall-through to products).
422 *
423 * @return string[]
424 */
425 private static function digest_object_types( string $collection ): array {
426 $row = Collections::row( $collection );
427
428 return isset( $row['digest']['object_types'] ) ? (array) $row['digest']['object_types'] : array();
429 }
430
431 /**
432 * `object_type = 'x'` for a single-type id-space, `object_type IN (...)` for a
433 * shared one. Values are registry constants, never request data.
434 *
435 * @param string[] $object_types Stored object types.
436 */
437 private static function object_type_predicate_sql( array $object_types ): string {
438 $quoted = array();
439 foreach ( $object_types as $object_type ) {
440 $quoted[] = "'" . $object_type . "'";
441 }
442
443 return 1 === \count( $quoted )
444 ? 'object_type = ' . $quoted[0]
445 : 'object_type IN (' . implode( ',', $quoted ) . ')';
446 }
447
448 /**
449 * Live-row predicate reused by the drill-down's deleted branch and the rebuild's orphan prune.
450 *
451 * @internal Engine-internal SQL fragment.
452 */
453 public function live_row_exists_sql( string $id_expr ): string {
454 global $wpdb;
455
456 return "EXISTS (SELECT 1 FROM {$wpdb->posts} lp WHERE lp.ID = {$id_expr}"
457 . ' AND lp.post_type IN ' . self::PRODUCT_POST_TYPES_SQL
458 . ' AND lp.post_status NOT IN ' . self::EXCLUDED_POST_STATUSES_SQL . ')';
459 }
460
461 /**
462 * Customer analogue of {@see live_row_exists_sql}: the id still names any WordPress user (ADR 0015).
463 *
464 * @internal Engine-internal SQL fragment.
465 */
466 public function customer_live_row_exists_sql( string $id_expr ): string {
467 global $wpdb;
468
469 return "EXISTS (SELECT 1 FROM {$wpdb->users} lu WHERE lu.ID = {$id_expr})";
470 }
471
472 /**
473 * Order analogue of {@see live_row_exists_sql} — HPOS/CPT-aware (ADR 0015, Leg-3 phase 7).
474 *
475 * @internal Engine-internal SQL fragment.
476 */
477 public function order_live_row_exists_sql( string $id_expr ): string {
478 global $wpdb;
479 if ( $this->orders_are_hpos() ) {
480 $orders_table = $wpdb->prefix . 'wc_orders';
481 return "EXISTS (SELECT 1 FROM {$orders_table} lo WHERE lo.id = {$id_expr}"
482 . " AND lo.type = 'shop_order' AND lo.status NOT IN ('trash','auto-draft'))";
483 }
484 return "EXISTS (SELECT 1 FROM {$wpdb->posts} lp WHERE lp.ID = {$id_expr}"
485 . " AND lp.post_type = 'shop_order' AND lp.post_status NOT IN " . self::EXCLUDED_POST_STATUSES_SQL . ')';
486 }
487
488 /**
489 * Stored-vs-current bucket aggregate over one id window (the integrity scan).
490 *
491 * Bucket aggregate: BIT_XOR over per-row 64-bit digests, deliberately instead of
492 * MD5(GROUP_CONCAT(... ORDER BY id)). XOR is commutative and associative, so the
493 * aggregate needs no ORDER BY and carries no group_concat_max_len truncation
494 * hazard; its state is a constant-size integer regardless of bucket population.
495 * Record counts travel alongside so add/delete imbalances that could cancel in
496 * XOR still flag.
497 *
498 * Digests are unsigned 64-bit (ADR 0014 M1) — above PHP_INT_MAX, so an (int) cast
499 * would SATURATE two distinct high-bit values to the same number and report a
500 * drifted bucket as `match`, hiding drift. They stay strings end to end.
501 *
502 * `max_id` is the larger of both sides' max id, so orphaned stored digests past
503 * the last live post still get scanned before the walk is called complete.
504 *
505 * @param array $range { Bucket window. @type int $bucket_size, @type int $start, @type int $end }
506 * @return array{buckets: array<int, array<string, mixed>>, max_id: int}
507 */
508 public function bucket_aggregates( array $range, string $collection = 'products', array $filters = array() ): array {
509 global $wpdb;
510 $bucket_size = max( 1, (int) ( $range['bucket_size'] ?? 1 ) );
511 $window_start = max( 0, (int) ( $range['start'] ?? 0 ) );
512 $window_end = max( 0, (int) ( $range['end'] ?? 0 ) );
513 $publish = 'products' === $collection && 'publish' === ( $filters['status'] ?? '' );
514 $object_types = self::OBJECT_TYPES_SQL;
515 $current_sql = $this->row_digest_select_sql( 'p.ID >= %d AND p.ID < %d' );
516 $max_sql = $this->row_digest_select_sql();
517 if ( 'customers' === $collection ) {
518 $object_types = "('customer')";
519 $current_sql = $this->customer_digest_select_sql( 'u.ID >= %d AND u.ID < %d' );
520 $max_sql = $this->customer_digest_select_sql();
521 } elseif ( 'orders' === $collection ) {
522 $object_types = "('order')";
523 $current_sql = $this->order_digest_select_sql( '{id} >= %d AND {id} < %d' );
524 $max_sql = $this->order_digest_select_sql();
525 }
526 $current_scope = $publish ? $this->product_servable_predicate_sql( 't.id', true ) : array(
527 'sql' => '',
528 'args' => array(),
529 );
530 $stored_scope = $publish ? $this->product_servable_predicate_sql( 'd.object_id', true ) : array(
531 'sql' => '',
532 'args' => array(),
533 );
534 $current_join = $publish ? " INNER JOIN {$wpdb->posts} catalog_post ON catalog_post.ID = t.id LEFT JOIN {$wpdb->posts} parent_product ON parent_product.ID = catalog_post.post_parent AND catalog_post.post_type = 'product_variation'" : '';
535 $stored_join = $publish ? " INNER JOIN {$wpdb->posts} catalog_post ON catalog_post.ID = d.object_id LEFT JOIN {$wpdb->posts} parent_product ON parent_product.ID = catalog_post.post_parent AND catalog_post.post_type = 'product_variation'" : '';
536
537 // Current side: one SQL pass — per-row canonical digests aggregated
538 // per bucket inside the DB engine. Raw rows are digested for
539 // DETECTION only; hydration goes through filtered REST (ADR 0003).
540 // Raise group_concat_max_len so the current-side digest matches the
541 // stored-side (written by the hook) byte-for-byte (ADR 0014 / no truncation drift).
542 $this->raise_group_concat_max_len();
543 $current_rows = $wpdb->get_results(
544 $wpdb->prepare(
545 'SELECT FLOOR(t.id / %d) AS bucket, COUNT(*) AS record_count, BIT_XOR(t.crc) AS digest'
546 . ' FROM (' . $current_sql . ') t' . $current_join . ( '' === $current_scope['sql'] ? '' : ' WHERE ' . $current_scope['sql'] )
547 . ' GROUP BY bucket ORDER BY bucket',
548 $bucket_size,
549 $window_start,
550 $window_end,
551 ...$current_scope['args']
552 ),
553 ARRAY_A
554 );
555
556 // Stored side: one SQL pass over the hook-maintained digest table.
557 $stored_rows = $wpdb->get_results(
558 $wpdb->prepare(
559 'SELECT FLOOR(d.object_id / %d) AS bucket, COUNT(*) AS record_count, BIT_XOR(d.digest) AS digest'
560 . ' FROM ' . $this->table_name() . ' d' . $stored_join
561 . ' WHERE d.object_type IN ' . $object_types
562 . ' AND d.object_id >= %d AND d.object_id < %d' . ( '' === $stored_scope['sql'] ? '' : ' AND ' . $stored_scope['sql'] )
563 . ' GROUP BY bucket ORDER BY bucket',
564 $bucket_size,
565 $window_start,
566 $window_end,
567 ...$stored_scope['args']
568 ),
569 ARRAY_A
570 );
571
572 $sides = array();
573 foreach ( \is_array( $stored_rows ) ? $stored_rows : array() as $row ) {
574 $sides[ (int) $row['bucket'] ]['stored'] = $row;
575 }
576 foreach ( \is_array( $current_rows ) ? $current_rows : array() as $row ) {
577 $sides[ (int) $row['bucket'] ]['current'] = $row;
578 }
579 ksort( $sides );
580
581 $buckets = array();
582 foreach ( $sides as $bucket => $side ) {
583 $stored_count = isset( $side['stored'] ) ? (int) $side['stored']['record_count'] : 0;
584 $current_count = isset( $side['current'] ) ? (int) $side['current']['record_count'] : 0;
585 $stored_digest = isset( $side['stored'] ) ? (string) $side['stored']['digest'] : '';
586 $current_digest = isset( $side['current'] ) ? (string) $side['current']['digest'] : '';
587 $buckets[] = array(
588 'bucket' => $bucket,
589 'range' => array(
590 'start' => $bucket * $bucket_size,
591 'end' => ( $bucket + 1 ) * $bucket_size,
592 ),
593 'stored_count' => $stored_count,
594 'current_count' => $current_count,
595 'stored_digest' => $stored_digest,
596 'current_digest' => $current_digest,
597 'match' => $stored_count === $current_count && $stored_digest === $current_digest,
598 );
599 }
600
601 $max_query =
602 'SELECT GREATEST('
603 . "COALESCE((SELECT MAX(ID) FROM {$wpdb->posts} WHERE post_type IN " . self::PRODUCT_POST_TYPES_SQL
604 . ' AND post_status NOT IN ' . self::EXCLUDED_POST_STATUSES_SQL . '), 0),'
605 . ' COALESCE((SELECT MAX(object_id) FROM ' . $this->table_name()
606 . ' WHERE object_type IN ' . self::OBJECT_TYPES_SQL . '), 0))';
607 $max_args = array();
608 if ( 'products' !== $collection || $publish ) {
609 $live_scope = $publish ? $this->product_servable_predicate_sql( 'live.id', true ) : array(
610 'sql' => '',
611 'args' => array(),
612 );
613 $live_join = $publish ? " INNER JOIN {$wpdb->posts} catalog_post ON catalog_post.ID = live.id LEFT JOIN {$wpdb->posts} parent_product ON parent_product.ID = catalog_post.post_parent AND catalog_post.post_type = 'product_variation'" : '';
614 $max_query = 'SELECT GREATEST(COALESCE((SELECT MAX(live.id) FROM (' . $max_sql . ') live' . $live_join . ( '' === $live_scope['sql'] ? '' : ' WHERE ' . $live_scope['sql'] ) . '), 0),'
615 . ' COALESCE((SELECT MAX(d.object_id) FROM ' . $this->table_name() . ' d'
616 . ' WHERE d.object_type IN ' . $object_types . '), 0))';
617 $max_args = $live_scope['args'];
618 }
619 $max_id = (int) $wpdb->get_var( empty( $max_args ) ? $max_query : $wpdb->prepare( $max_query, ...$max_args ) );
620
621 return array(
622 'buckets' => $buckets,
623 'max_id' => $max_id,
624 );
625 }
626
627 /**
628 * Per-id stored-vs-current comparison inside ONE bucket (the scan drill-down).
629 *
630 * Three mismatch shapes: changed (both sides present, digests differ),
631 * missing_stored (live row never digested — created without hooks or
632 * pre-backfill), deleted (stored digest whose row is gone — hook-bypassing
633 * delete). Digests stay strings (ADR 0014 M1) and are null where the side is
634 * absent.
635 *
636 * @param array $range { Bucket window. @type int $start, @type int $end }
637 *
638 * @return array<int, array<string, mixed>>
639 */
640 public function bucket_drift( array $range ): array {
641 global $wpdb;
642 $range_start = max( 0, (int) ( $range['start'] ?? 0 ) );
643 $range_end = max( 0, (int) ( $range['end'] ?? 0 ) );
644 $table = $this->table_name();
645
646 // Same-formula invariant: the current side must digest identically to the stored side.
647 $this->raise_group_concat_max_len();
648 $rows = $wpdb->get_results(
649 $wpdb->prepare(
650 'SELECT cur.id AS id,'
651 . " CASE WHEN d.digest IS NULL THEN 'missing_stored' ELSE 'changed' END AS status,"
652 . ' d.digest AS stored_digest, cur.crc AS current_digest, cur.object_type AS object_type'
653 . ' FROM (' . $this->row_digest_select_sql( 'p.ID >= %d AND p.ID < %d' ) . ') cur'
654 . " LEFT JOIN {$table} d ON d.object_id = cur.id AND d.object_type = cur.object_type"
655 . ' WHERE d.digest IS NULL OR d.digest <> cur.crc'
656 . ' UNION ALL'
657 . " SELECT d.object_id AS id, 'deleted' AS status, d.digest AS stored_digest, NULL AS current_digest, d.object_type AS object_type"
658 . " FROM {$table} d"
659 . ' WHERE d.object_type IN ' . self::OBJECT_TYPES_SQL
660 . ' AND d.object_id >= %d AND d.object_id < %d'
661 . ' AND NOT ' . $this->live_row_exists_sql( 'd.object_id' )
662 . ' ORDER BY id ASC',
663 $range_start,
664 $range_end,
665 $range_start,
666 $range_end
667 ),
668 ARRAY_A
669 );
670
671 return array_map(
672 static function ( array $row ): array {
673 return array(
674 'id' => (int) $row['id'],
675 'status' => (string) $row['status'],
676 'object_type' => (string) ( $row['object_type'] ?? '' ),
677 // Unsigned 64-bit (ADR 0014 M1): keep as strings — a (int) cast (and JS Number) can't
678 // hold values above PHP_INT_MAX / 2^53 without precision loss.
679 'stored_digest' => null === $row['stored_digest'] ? null : (string) $row['stored_digest'],
680 'current_digest' => null === $row['current_digest'] ? null : (string) $row['current_digest'],
681 );
682 },
683 \is_array( $rows ) ? $rows : array()
684 );
685 }
686
687 /**
688 * The authoritative current {id, digest, object_type} for every live SERVABLE record whose id falls
689 * in the given range of the collection's own id-space (products/variations over wp_posts, customers
690 * over wp_users, orders over HPOS or CPT). Digests come from the SAME 64-bit formula the client's
691 * manifest stores, so the two compare apples-to-apples.
692 *
693 * Products carry the servable scoping the pull filter applies, so the reconcile prunes anything the
694 * POS may no longer see: the optional `status => publish` readable-catalog filter, and ALWAYS the
695 * POS-hidden (`online_only`) ids. READ-SIDE ONLY — a visibility toggle changes no product row (no
696 * hook fires), so stored per-record digests are never touched; omitting the ids from this read is
697 * enough because the client folds THIS list. Products and variations share the wp_posts id-space, so
698 * their two hidden lists union safely on cur.id.
699 *
700 * @param string $collection Digest id-space owner: products | customers | orders.
701 * @param array $range { @type int $start, @type int $end }
702 * @param array $filters { @type string $status 'publish' scopes products to the readable catalog. }
703 *
704 * @return array<int, array{id: int, digest: string, object_type: string}>
705 */
706 public function bucket_listing( string $collection, array $range, array $filters = array() ): array {
707 global $wpdb;
708 $range_start = max( 0, (int) ( $range['start'] ?? 0 ) );
709 $range_end = max( 0, (int) ( $range['end'] ?? 0 ) );
710
711 $servable_join = '';
712 $servable_filter = '';
713 $servable_args = array();
714 if ( 'customers' === $collection ) {
715 $inner_sql = $this->customer_digest_select_sql( 'u.ID >= %d AND u.ID < %d' );
716 } elseif ( 'orders' === $collection ) {
717 // Orders bucket over their own id-space (HPOS o.id / CPT p.ID) via the {id} placeholder.
718 $inner_sql = $this->order_digest_select_sql( '{id} >= %d AND {id} < %d' );
719 } else {
720 $inner_sql = $this->row_digest_select_sql( 'p.ID >= %d AND p.ID < %d' );
721 $servable_join = " INNER JOIN {$wpdb->posts} catalog_post ON catalog_post.ID = cur.id";
722 if ( 'publish' === ( $filters['status'] ?? '' ) ) {
723 $servable_join .= " LEFT JOIN {$wpdb->posts} parent_product ON parent_product.ID = catalog_post.post_parent"
724 . " AND catalog_post.post_type = 'product_variation'";
725 }
726 $servable = $this->product_servable_predicate_sql( 'cur.id', 'publish' === ( $filters['status'] ?? '' ) );
727 $servable_filter = '' === $servable['sql'] ? '' : ' WHERE ' . $servable['sql'];
728 $servable_args = $servable['args'];
729 }
730
731 // Same-formula invariant + GROUP_CONCAT stability, exactly as the scan's current side.
732 $this->raise_group_concat_max_len();
733 $rows = $wpdb->get_results(
734 $wpdb->prepare(
735 'SELECT cur.id AS id, cur.crc AS digest, cur.object_type AS object_type FROM ('
736 . $inner_sql
737 . ') cur' . $servable_join . $servable_filter . ' ORDER BY cur.id ASC',
738 $range_start,
739 $range_end,
740 ...$servable_args
741 ),
742 ARRAY_A
743 );
744
745 return array_map(
746 static function ( array $row ): array {
747 return array(
748 'id' => (int) $row['id'],
749 // Unsigned 64-bit (ADR 0014 M1): keep as a string — (int)/JS Number lose precision above 2^53.
750 'digest' => (string) $row['digest'],
751 'object_type' => (string) $row['object_type'],
752 );
753 },
754 \is_array( $rows ) ? $rows : array()
755 );
756 }
757
758 /**
759 * Narrow product-space ids to the readable catalog: published products, and variations whose parent
760 * product is published. The SAME rule {@see bucket_listing} applies with `status => publish`, so the
761 * prime-pass digest read and the reconcile listing can never disagree about what "publish" means.
762 *
763 * @param int[] $ids Requested product-space ids.
764 *
765 * @return int[] The subset that is readable, in the caller's order.
766 */
767 public function published_product_ids( array $ids ): array {
768 global $wpdb;
769 $ids = array_values( array_map( 'intval', $ids ) );
770 if ( array() === $ids ) {
771 return array();
772 }
773 $placeholders = implode( ',', array_fill( 0, \count( $ids ), '%d' ) );
774 $published_ids = $wpdb->get_col(
775 $wpdb->prepare(
776 "SELECT p.ID FROM {$wpdb->posts} p"
777 . " LEFT JOIN {$wpdb->posts} parent ON parent.ID = p.post_parent AND p.post_type = 'product_variation'"
778 . ' WHERE p.ID IN (' . $placeholders . ')'
779 . ' AND ' . $this->published_product_predicate_sql( 'p', 'parent' ),
780 ...$ids
781 )
782 );
783
784 return array_values( array_intersect( $ids, array_map( 'intval', (array) $published_ids ) ) );
785 }
786
787 /** Narrow product-space ids to the integrity scan's canonical servable membership. */
788 public function servable_product_ids( array $ids, bool $publish = false ): array {
789 global $wpdb;
790 $ids = array_values( array_map( 'intval', $ids ) );
791 if ( array() === $ids ) {
792 return array();
793 }
794 $placeholders = implode( ',', array_fill( 0, \count( $ids ), '%d' ) );
795 $servable = $this->product_servable_predicate_sql( 'catalog_post.ID', $publish );
796 $query_args = array_merge( $ids, $servable['args'] );
797 $servable_ids = $wpdb->get_col(
798 $wpdb->prepare(
799 "SELECT catalog_post.ID FROM {$wpdb->posts} catalog_post"
800 . ( $publish ? " LEFT JOIN {$wpdb->posts} parent_product ON parent_product.ID = catalog_post.post_parent AND catalog_post.post_type = 'product_variation'" : '' )
801 . ' WHERE catalog_post.ID IN (' . $placeholders . ') AND ' . $servable['sql'],
802 ...$query_args
803 )
804 );
805
806 return array_values( array_intersect( $ids, array_map( 'intval', (array) $servable_ids ) ) );
807 }
808
809 /**
810 * True when the product space holds live rows but carries NO stored digests at all — the
811 * "stored side was never backfilled (or was wiped)" signal the scan answers with a guarded rebuild
812 * instead of reporting the whole catalog as drift.
813 */
814 public function needs_product_rebuild(): bool {
815 global $wpdb;
816
817 return (bool) $wpdb->get_var(
818 'SELECT EXISTS (SELECT 1 FROM ' . $wpdb->posts
819 . ' WHERE post_type IN ' . self::PRODUCT_POST_TYPES_SQL
820 . ' AND post_status NOT IN ' . self::EXCLUDED_POST_STATUSES_SQL . ' LIMIT 1)'
821 . ' AND NOT EXISTS (SELECT 1 FROM ' . $this->table_name()
822 . ' WHERE object_type IN ' . self::OBJECT_TYPES_SQL . ' LIMIT 1)'
823 );
824 }
825
826 /**
827 * The readable-catalog predicate over a post alias and its parent alias — a published product,
828 * or a variation whose parent product is published. One home for the rule.
829 */
830 private function published_product_predicate_sql( string $post_alias, string $parent_alias ): string {
831 return "(({$post_alias}.post_type = 'product' AND {$post_alias}.post_status = 'publish')"
832 . " OR ({$post_alias}.post_type = 'product_variation' AND {$parent_alias}.post_type = 'product'"
833 . " AND {$parent_alias}.post_status = 'publish'))";
834 }
835
836 private function product_servable_predicate_sql( string $id_expr, bool $publish ): array {
837 $predicates = array(
838 'catalog_post.post_type IN ' . self::PRODUCT_POST_TYPES_SQL,
839 'catalog_post.post_status NOT IN ' . self::EXCLUDED_POST_STATUSES_SQL,
840 );
841 if ( $publish ) {
842 $predicates[] = $this->published_product_predicate_sql( 'catalog_post', 'parent_product' );
843 }
844 $hidden = $this->pos_hidden_product_ids();
845 if ( array() !== $hidden ) {
846 $predicates[] = $id_expr . ' NOT IN (' . implode( ',', array_fill( 0, \count( $hidden ), '%d' ) ) . ')';
847 }
848 return array(
849 'sql' => implode( ' AND ', $predicates ),
850 'args' => $hidden,
851 );
852 }
853
854 /**
855 * Product-space ids hidden from the POS (`online_only`), products and variations unioned — they share
856 * the wp_posts id-space. Read through the {@see Pos_Visibility} contract, never from the option.
857 *
858 * @return int[]
859 */
860 private function pos_hidden_product_ids(): array {
861 return array_values(
862 array_unique(
863 array_map(
864 'intval',
865 array_merge(
866 $this->visibility->online_only_product_ids(),
867 $this->visibility->online_only_variation_ids()
868 )
869 )
870 )
871 );
872 }
873
874 /** True when orders use HPOS (WooCommerce's own tables); false → legacy CPT (wp_posts). */
875 private function orders_are_hpos(): bool {
876 $order_util = '\\Automattic\\WooCommerce\\Utilities\\OrderUtil';
877 if ( class_exists( $order_util ) && method_exists( $order_util, 'custom_orders_table_usage_is_enabled' ) ) {
878 return (bool) call_user_func( array( $order_util, 'custom_orders_table_usage_is_enabled' ) );
879 }
880 return false; // no WC / older WC → CPT
881 }
882 }
883