`. The title, short * description (excerpt) and description stay with the core / classic / Gutenberg adapters. * * Every value is read with WC_Product getters ('edit' context) and written with WC_Product setters * and save() — WooCommerce's own data store, which keeps `_price`, the product lookup table and its * caches in step and is HPOS-compatible. Prices are money: they are labelled with the store currency, * checked strictly (no negative, malformed or over-precise amounts; a sale below the regular price) * before any restore point is taken, and changed one field per call so ADI's approval card shows each * before → after. Store settings (currency, tax, shipping), orders, customers, coupons and payments * are never writable here. * * Simple products' prices, SKU, stock and attributes are editable; variable products list their variations, and * each variation's prices, sale dates, SKU, stock, enabled status and image are editable one field per call * (`variations//`, #22) through WC_Product_Variation setters, after which the parent is synced. Categories, tags, the featured image and the gallery (#21) are editable on simple and * variable products: existing terms and Media Library images only, through the same setters. */ final class WooCommerce implements Adapter { /** * Product meta WooCommerce's setters write for the price fields and SKU: restorable on simple products (#15). * Not `_price`, the active price: it is derived (WooCommerce's scheduled sales rewrite it alone), so a restore * recomputes it from the restored prices and sale window instead of putting back a stale one. */ const META = array( '_regular_price', '_sale_price', '_sale_price_dates_from', '_sale_price_dates_to', '_sku' ); /** Of META, the price meta: not restorable while price writing is switched off. */ const PRICE_META = array( '_regular_price', '_sale_price', '_sale_price_dates_from', '_sale_price_dates_to' ); /** * Stock meta (with what WooCommerce resets when stock tracking is turned off): restorable only by a * restore point taken for a stock change (orders move stock meanwhile). */ const STOCK_META = array( '_manage_stock', '_stock', '_stock_status', '_backorders', '_low_stock_amount' ); /** Prices of products about to be restored: id => array( regular, sale ), for the restore result. */ private static $restoring = array(); /** The same for the variations a restore puts back (#22): parent id => variation id => shop state. */ private static $restoring_children = array(); /** Variation summaries listed per variable product (the rest are counted). */ const MAX_VARIATIONS = 50; /** Fields whose restore points may put stock back. */ const STOCK_FIELDS = array( 'manage_stock', 'stock_quantity', 'stock_status' ); const PRICE_FIELDS = array( 'regular_price', 'sale_price', 'date_on_sale_from', 'date_on_sale_to' ); /** A variation field's locator (#22): variations//. */ const VARIATION_RE = '#^variations/(\d+)/([a-z_]+)\z#'; /** What ADI changes on a variation (one per call). */ const VARIATION_PROPS = array( 'regular_price', 'sale_price', 'date_on_sale_from', 'date_on_sale_to', 'sku', 'manage_stock', 'stock_quantity', 'stock_status', 'enabled', 'image' ); /** True while read() builds the fields for one locator (no term choices or variation summaries). */ private $light = false; /** Product taxonomies ADI assigns existing terms of (#21): locator => taxonomy. */ const TAXONOMIES = array( 'categories' => 'product_cat', 'tags' => 'product_tag' ); /** * Catalog meta the #21 fields write, restorable on simple and variable products (the featured image, * `_thumbnail_id`, already is on every post). */ const CATALOG_META = array( '_product_image_gallery' ); /** The product's attribute list: restorable on simple products by merging local values only (restore_meta()). */ const ATTRIBUTES_META = '_product_attributes'; /** Terms offered as `choices` per taxonomy (any existing term id is accepted). */ const MAX_CHOICES = 200; /** Terms, gallery images and attribute values per write. */ const MAX_TERMS = 100; const MAX_GALLERY = 50; const MAX_VALUES = 100; public static function boot() { add_action( 'adibridge_before_restore', array( self::class, 'before_restore' ), 10, 2 ); add_action( 'adibridge_after_restore', array( self::class, 'after_restore' ), 5 ); add_action( 'adibridge_check_restore', array( self::class, 'check_restore' ), 10, 4 ); add_filter( 'adibridge_snapshot_children', array( self::class, 'snapshot_children' ), 10, 3 ); add_filter( 'adibridge_write_result', array( self::class, 'label_result' ) ); add_filter( 'adibridge_snapshot_taxonomies', array( self::class, 'snapshot_taxonomies' ), 10, 2 ); add_filter( 'adibridge_restore_meta', array( self::class, 'restore_meta' ), 10, 4 ); } public function id() { return 'woocommerce'; } public function name() { return 'WooCommerce'; } /** * WooCommerce 10.8+ (the product data store's public refresh_product_lookup_table(), which keeps a * restored SKU or price visible to WooCommerce's lookups and uniqueness checks). */ public function available() { return class_exists( '\WooCommerce' ) && function_exists( 'wc_get_product' ) && function_exists( 'get_woocommerce_currency' ) && method_exists( 'WC_Product_Data_Store_CPT', 'refresh_product_lookup_table' ); } public function detect( \WP_Post $post ) { return 'product' === $post->post_type; } public function post_column( $locator ) { return null; // product data lives in meta and lookup tables, written by WooCommerce's data store } /** Store currency code (CAD). */ public static function currency() { return (string) get_woocommerce_currency(); } /** Store currency symbol as plain text ($). */ public static function symbol() { return html_entity_decode( (string) get_woocommerce_currency_symbol(), ENT_QUOTES, 'UTF-8' ); } /** A price as a person reads it: "$49.99 CAD", or "(none)". */ public static function money( $value ) { return '' === (string) $value || null === $value ? '(none)' : self::symbol() . $value . ' ' . self::currency(); } private static function product( \WP_Post $post ) { $product = wc_get_product( $post->ID ); if ( ! $product ) { throw new Tool_Error( esc_html( "WooCommerce can't load product #{$post->ID}. Nothing was changed." ) ); } return $product; } /** May prices be changed through ADI on this site? The one switch for price writing (and restoring). */ private static function prices_writable( \WP_Post $post ) { return (bool) apply_filters( 'adibridge_woocommerce_prices_writable', true, $post ); } /** prices_writable() for a post id (Snapshots). */ public static function prices_writable_for( $id ) { $post = get_post( (int) $id ); return $post ? self::prices_writable( $post ) : false; } /** * Is $id a product whose WooCommerce meta a restore may put back? Simple products only: a variable or * grouped parent's prices are synced from its children, and the adapter doesn't write them. */ public static function restorable_product( $id ) { if ( 'product' !== get_post_type( (int) $id ) || ! function_exists( 'wc_get_product' ) ) { return false; } $product = wc_get_product( (int) $id ); return $product && $product->is_type( 'simple' ); } /** * Is $id a product whose catalog data (categories, tags, images) ADI edits and a restore may put back? * Simple and variable products: those belong to the product itself, not to its variations. */ public static function catalog_product( $id ) { if ( 'product' !== get_post_type( (int) $id ) || ! function_exists( 'wc_get_product' ) ) { return false; } $product = wc_get_product( (int) $id ); return $product && $product->is_type( array( 'simple', 'variable' ) ); } /** Restore points of catalog products record their category and tag relationships (Snapshots). */ public static function snapshot_taxonomies( $taxonomies, $id ) { if ( is_int( $id ) && self::catalog_product( $id ) ) { foreach ( self::TAXONOMIES as $taxonomy ) { if ( taxonomy_exists( $taxonomy ) ) { $taxonomies[] = $taxonomy; } } } return $taxonomies; } /** * A sale date as stored: YYYY-MM-DD when it is at the day boundary wp-admin uses (00:00:00 for a start, * 23:59:59 for an end), else with its time (set elsewhere, e.g. the REST API) so a put-back is exact. */ private static function date_value( $date, $boundary = '00:00:00' ) { if ( ! $date ) { return ''; } return $date->date( 'H:i:s' ) === $boundary ? $date->date( 'Y-m-d' ) : $date->date( 'Y-m-d H:i:s' ); } public function list_fields( \WP_Post $post ) { $product = wc_get_product( $post->ID ); if ( ! $product ) { return array( array( 'locator' => 'product', 'label' => 'Product data', 'type' => 'readonly', 'value' => null, 'writable' => false, 'note' => 'WooCommerce could not load this product.', ), ); } $cur = self::currency(); $sym = self::symbol(); $simple = $product->is_type( 'simple' ); $editable = $simple && current_user_can( 'edit_product', $post->ID ); $prices = $editable && self::prices_writable( $post ); $why = $simple ? '' : ' Read-only: this is a ' . $product->get_type() . ' product, and ADI edits simple products\' and variations\' prices, SKU and stock (variations: below). Change it in WooCommerce → Products.'; $no_price = $simple && ! self::prices_writable( $post ) ? ' Read-only: price changes through ADI are switched off on this site.' : ''; $fields = array(); if ( ! $product->is_type( array( 'variable', 'grouped' ) ) ) { $fields = self::price_fields( $product, '', $prices, $why . $no_price ); } $fields = array_merge( $fields, self::stock_fields( $product, '', $editable, $why, false ) ); $fields = array_merge( $fields, $this->catalog_fields( $post, $product ) ); $fields[] = array( 'locator' => 'currency', 'label' => 'Store currency', 'type' => 'readonly', 'value' => $cur, 'writable' => false, 'note' => "All prices are in $cur ($sym). Currency, tax and shipping are store settings (WooCommerce → Settings) that ADI never changes.", ); if ( $product->is_type( 'variable' ) && ! $this->light ) { $children = $product->get_children(); if ( count( $children ) > self::MAX_VARIATIONS ) { $fields[] = array( 'locator' => 'variations', 'label' => 'Variations', 'type' => 'readonly', 'value' => count( $children ) . ' variations', 'writable' => false, 'note' => 'The first ' . self::MAX_VARIATIONS . ' are listed below; see the rest in WooCommerce → Products.', ); $children = array_slice( $children, 0, self::MAX_VARIATIONS ); } $paths = implode( ', ', self::VARIATION_PROPS ); foreach ( $children as $child_id ) { $variation = wc_get_product( $child_id ); if ( ! $variation || ! $variation->is_type( 'variation' ) ) { continue; } $fields[] = array( 'locator' => 'variations/' . (int) $child_id, 'label' => 'Variation: ' . self::variation_name( $variation ), 'type' => 'readonly', 'value' => self::variation_summary( $variation ), 'writable' => false, 'note' => "Prices in $cur ($sym), the store currency. " . self::variation_text( $variation ) . '. To change one value, call wp_update_field with the path woocommerce:variations/' . (int) $child_id . "/, one of: $paths (one change per call; the variation's attributes can't be changed through ADI).", ); } } return $fields; } /** Regular and sale price and the sale dates of a simple product or a variation, as fields under $prefix. */ private static function price_fields( $product, $prefix, $writable, $suffix ) { $cur = self::currency(); $sym = self::symbol(); $money = " ($cur, $sym)"; $in_cur = "In $cur ($sym), the store currency — a WooCommerce setting ADI never changes."; $tz = wp_timezone_string(); return array( array( 'locator' => $prefix . 'regular_price', 'label' => "Regular price$money", 'type' => 'text', 'value' => (string) $product->get_regular_price( 'edit' ), 'writable' => $writable, 'currency' => $cur, 'note' => "$in_cur A decimal number such as 49.99, without a currency sign; at most " . wc_get_price_decimals() . ' decimals. It can\'t be emptied.' . $suffix, ), array( 'locator' => $prefix . 'sale_price', 'label' => "Sale price$money", 'type' => 'text', 'value' => (string) $product->get_sale_price( 'edit' ), 'writable' => $writable, 'currency' => $cur, 'note' => "$in_cur Must be below the regular price. Empty ends the sale. The sale dates below limit when it applies." . $suffix, ), array( 'locator' => $prefix . 'date_on_sale_from', 'label' => "Sale starts (date) — sale price in $cur", 'type' => 'text', 'value' => self::date_value( $product->get_date_on_sale_from( 'edit' ) ), 'writable' => $writable, 'note' => "YYYY-MM-DD in the site's timezone ($tz): the sale price ($cur) applies from 00:00 that day. Empty: the sale applies now." . $suffix, ), array( 'locator' => $prefix . 'date_on_sale_to', 'label' => "Sale ends (date) — sale price in $cur", 'type' => 'text', 'value' => self::date_value( $product->get_date_on_sale_to( 'edit' ), '23:59:59' ), 'writable' => $writable, 'note' => "YYYY-MM-DD in the site's timezone ($tz): the sale price ($cur) applies until 23:59 that day, then the regular price. Empty: no end date." . $suffix, ), ); } /** * SKU and stock of a product or a variation, as fields under $prefix. $parent_stock: the variation's parent * tracks stock (a variation that doesn't track its own then takes the parent's, so its status is derived). */ private static function stock_fields( $product, $prefix, $editable, $why, $parent_stock ) { $managed = (bool) $product->get_manage_stock( 'edit' ); $qty = $product->get_stock_quantity( 'edit' ); $derived = $managed || $parent_stock; return array( array( 'locator' => $prefix . 'sku', 'label' => 'SKU', 'type' => 'text', 'value' => (string) $product->get_sku( 'edit' ), 'writable' => $editable, 'note' => 'Stock-keeping unit; must be unique across the store\'s products and variations. Empty removes it.' . $why, ), array( 'locator' => $prefix . 'manage_stock', 'label' => 'Track stock quantity', 'type' => 'boolean', 'value' => $managed, 'writable' => $editable, 'note' => 'When on, WooCommerce counts stock down with each order and sets the stock status from the quantity (with no quantity yet, the product shows out of stock until one is set). Turning it off clears the quantity, the low-stock threshold and allows no backorders.' . $why, ), array( 'locator' => $prefix . 'stock_quantity', 'label' => 'Stock quantity', 'type' => 'number', 'value' => null === $qty || '' === $qty ? null : (int) $qty, 'writable' => $editable && $managed, 'note' => ( $managed ? 'Units in stock, a whole number (negative while on backorder). Orders change it: read it right before changing it and pass the value read as `expected`, so a sale in between isn\'t overwritten.' : 'Read-only: stock isn\'t tracked for this product (turn on "Track stock quantity" first).' ) . $why, ), array( 'locator' => $prefix . 'stock_status', 'label' => 'Stock status', 'type' => 'select', 'value' => (string) $product->get_stock_status( 'edit' ), 'choices' => wc_get_product_stock_status_options(), 'writable' => $editable && ! $derived, 'note' => ( $managed ? 'Read-only: WooCommerce sets it from the stock quantity while stock is tracked.' : ( $parent_stock ? 'Read-only: the product tracks stock for this variation, and WooCommerce sets the status from it.' : 'In stock, out of stock or on backorder.' ) ) . $why, ), ); } /** The variation $id of the variable product $post, or null (missing, not a variation, another product's). */ private static function variation_of( \WP_Post $post, $id ) { $variation = $id > 0 && 'product_variation' === get_post_type( $id ) ? wc_get_product( $id ) : null; // Enabled (publish) or disabled (private), as wp-admin lists them: not drafts or trashed ones. return $variation && $variation->is_type( 'variation' ) && (int) $variation->get_parent_id( 'edit' ) === (int) $post->ID && in_array( $variation->get_status( 'edit' ), array( 'publish', 'private' ), true ) ? $variation : null; } /** * One variation's fields (#22): prices, sale dates, SKU, stock, enabled and image, under variations//. * Resolved on read and write; the listing shows one summary per variation instead (variation_summary()). */ private static function variation_fields( \WP_Post $post, $variation ) { $parent = wc_get_product( $post->ID ); $editable = current_user_can( 'edit_product', $post->ID ) && current_user_can( 'edit_post', $variation->get_id() ); $type = get_post_type_object( 'product' ); $publish = $editable && $type && current_user_can( $type->cap->publish_posts ); $no_price = self::prices_writable( $post ) ? '' : ' Read-only: price changes through ADI are switched off on this site.'; $prefix = 'variations/' . $variation->get_id() . '/'; $name = self::variation_name( $variation ); $fields = array_merge( self::price_fields( $variation, $prefix, $editable && self::prices_writable( $post ), $no_price ), self::stock_fields( $variation, $prefix, $editable, '', $parent && (bool) $parent->get_manage_stock( 'edit' ) ) ); $fields[] = array( 'locator' => $prefix . 'enabled', 'label' => 'Enabled', 'type' => 'boolean', 'value' => 'publish' === $variation->get_status( 'edit' ), 'writable' => $publish, 'note' => 'Whether customers can choose this variation (wp-admin\'s "Enabled"). Off keeps it, hidden from the shop.' . ( $editable && ! $publish ? ' Read-only: the connected WordPress user may not publish products.' : '' ), ); $fields[] = array( 'locator' => $prefix . 'image', 'label' => 'Variation image', 'type' => 'image', 'value' => (int) $variation->get_image_id( 'edit' ), 'writable' => $editable, 'note' => 'Shown when a customer picks this variation: a Media Library image ID (use wp_search_media), or 0 to remove it (the product image shows). Now: ' . self::show_images( array( (int) $variation->get_image_id( 'edit' ) ) ) . '.', ); foreach ( $fields as $i => $field ) { $fields[ $i ]['label'] = "Variation $name — " . $field['label']; } return $fields; } /** A variation's attribute combination as a person reads it: "Size: Small, Colour: Red" (term names, not slugs). */ private static function variation_name( $variation ) { $parts = array(); foreach ( self::variation_attributes( $variation ) as $label => $value ) { $parts[] = "$label: $value"; } return $parts ? implode( ', ', $parts ) : '#' . $variation->get_id(); } /** label => value of a variation's attributes ("any" for an attribute it doesn't fix). */ private static function variation_attributes( $variation ) { $out = array(); foreach ( $variation->get_attributes( 'edit' ) as $name => $value ) { $name = str_replace( 'attribute_', '', (string) $name ); $value = (string) $value; if ( '' !== $value && taxonomy_exists( $name ) ) { $term = get_term_by( 'slug', $value, $name ); $value = $term instanceof \WP_Term ? $term->name : $value; } $out[ html_entity_decode( wc_attribute_label( $name, $variation ), ENT_QUOTES, 'UTF-8' ) ] = '' === $value ? 'any' : $value; } return $out; } /** A variation's current values, for the listing (the paths under variations// change them). */ private static function variation_summary( $variation ) { $qty = $variation->get_stock_quantity( 'edit' ); return array( 'id' => $variation->get_id(), 'attributes' => self::variation_attributes( $variation ), 'regular_price' => (string) $variation->get_regular_price( 'edit' ), 'sale_price' => (string) $variation->get_sale_price( 'edit' ), 'date_on_sale_from' => self::date_value( $variation->get_date_on_sale_from( 'edit' ) ), 'date_on_sale_to' => self::date_value( $variation->get_date_on_sale_to( 'edit' ), '23:59:59' ), 'sku' => (string) $variation->get_sku( 'edit' ), 'manage_stock' => (bool) $variation->get_manage_stock( 'edit' ), 'stock_quantity' => null === $qty || '' === $qty ? null : (int) $qty, 'stock_status' => (string) $variation->get_stock_status( 'edit' ), 'enabled' => 'publish' === $variation->get_status( 'edit' ), 'image' => (int) $variation->get_image_id( 'edit' ), 'currency' => self::currency(), ); } /** The same as a person reads it: "Regular price $34.00 CAD · Sale price (none) · SKU … · Stock 5 (In stock) · Enabled". */ private static function variation_text( $variation ) { $qty = $variation->get_stock_quantity( 'edit' ); $opts = wc_get_product_stock_status_options(); $stat = (string) $variation->get_stock_status( 'edit' ); return implode( ' · ', array( 'Regular price ' . self::money( $variation->get_regular_price( 'edit' ) ), 'Sale price ' . self::money( $variation->get_sale_price( 'edit' ) ), 'SKU ' . ( '' === (string) $variation->get_sku( 'edit' ) ? '(none)' : $variation->get_sku( 'edit' ) ), 'Stock ' . ( null === $qty || '' === $qty ? 'not tracked' : (int) $qty ) . ' (' . ( isset( $opts[ $stat ] ) ? $opts[ $stat ] : $stat ) . ')', 'publish' === $variation->get_status( 'edit' ) ? 'Enabled' : 'Disabled', ) ); } // ── Catalog: categories, tags, images, attributes (#21) ─────────────────────────────── /** Categories, tags, featured image, gallery and attributes of $product, as fields. */ private function catalog_fields( \WP_Post $post, $product ) { $catalog = $product->is_type( array( 'simple', 'variable' ) ); $can = $catalog && current_user_can( 'edit_product', $post->ID ); $why = $catalog ? '' : ' Read-only: this is a ' . $product->get_type() . ' product; ADI changes the categories, tags and images of simple and variable products. Change it in WooCommerce → Products.'; $fields = array(); foreach ( self::TAXONOMIES as $locator => $taxonomy ) { $tax = get_taxonomy( $taxonomy ); if ( ! $tax ) { continue; } $plural = 'categories' === $locator ? 'categories' : 'tags'; $assign = $can && current_user_can( $tax->cap->assign_terms ); $ids = self::term_ids( $product, $locator ); $choices = array(); $terms = $this->light ? array() : get_terms( array( 'taxonomy' => $taxonomy, 'hide_empty' => false, 'number' => self::MAX_CHOICES + 1, 'orderby' => 'name' ) ); $terms = is_array( $terms ) ? $terms : array(); $more = count( $terms ) > self::MAX_CHOICES ? ' Only the first ' . self::MAX_CHOICES . ' (by name) are listed in choices; any existing ' . rtrim( $plural, 's' ) . ' ID works.' : ''; foreach ( array_slice( $terms, 0, self::MAX_CHOICES ) as $term ) { $choices[ (int) $term->term_id ] = self::term_name( $term ); } $default = 'categories' === $locator ? ' An empty list puts the product in the store\'s default category, as WooCommerce does.' : ' An empty list removes every tag.'; $fields[] = array( 'locator' => $locator, 'label' => 'categories' === $locator ? 'Product categories' : 'Product tags', 'type' => 'json', 'value' => $ids, 'choices' => $choices, 'writable' => $assign, 'note' => 'Now: ' . self::show_terms( $ids, $taxonomy ) . ". A list of existing product $plural' IDs (from choices), e.g. [12, 15]; it replaces the whole list." . $default . " ADI doesn't create new $plural: add one in WooCommerce → Products → " . ucfirst( $plural ) . ' first.' . $more . ( $can && ! $assign ? " Read-only: the connected WordPress user may not assign product $plural." : '' ) . $why, ); } $fields[] = array( 'locator' => 'featured_image', 'label' => 'Product image', 'type' => 'image', 'value' => (int) $product->get_image_id( 'edit' ), 'writable' => $can, 'note' => 'The main product image: a Media Library image ID (use wp_search_media), or 0 to remove it. Now: ' . self::show_images( array( (int) $product->get_image_id( 'edit' ) ) ) . '.' . $why, ); $gallery = self::gallery_ids( $product ); $fields[] = array( 'locator' => 'gallery', 'label' => 'Product gallery', 'type' => 'json', 'value' => $gallery, 'writable' => $can, 'note' => 'The extra product images, in order: a list of Media Library image IDs (use wp_search_media), e.g. [41, 42]; it replaces the whole list, [] removes them all. At most ' . self::MAX_GALLERY . '. Now: ' . self::show_images( $gallery ) . '.' . $why, ); $simple = $product->is_type( 'simple' ); $tidy = self::attributes_tidy( $product ); foreach ( $product->get_attributes( 'edit' ) as $key => $attribute ) { if ( ! $attribute instanceof \WC_Product_Attribute ) { continue; } $name = wc_attribute_label( $attribute->get_name(), $product ); $global = $attribute->is_taxonomy(); if ( $global ) { $terms = $attribute->get_terms(); $value = is_array( $terms ) ? array_values( wp_list_pluck( $terms, 'name' ) ) : array(); $note = 'Read-only: a global attribute (WooCommerce → Products → Attributes); its terms are managed there, and ADI doesn\'t change global attributes.'; } elseif ( $attribute->get_variation() ) { $value = array_values( $attribute->get_options() ); $note = 'Read-only: used for variations — changing its values would change which variations exist.'; } elseif ( ! $simple ) { $value = array_values( $attribute->get_options() ); $note = 'Read-only: this is a ' . $product->get_type() . ' product; ADI changes attribute values of simple products. Change it in WooCommerce → Products.'; } elseif ( ! $tidy ) { $value = array_values( $attribute->get_options() ); $note = 'Read-only: this product\'s attribute list is stored in an older form. Open the product in wp-admin and update it once, then ADI can change it.'; } else { $value = array_values( $attribute->get_options() ); $note = 'This product\'s own attribute (shown under "Additional information"): its values, a list of plain-text strings such as ["Leather", "Canvas"]; it replaces the whole list. ADI changes the values only — add, remove or rename attributes in WooCommerce → Products.'; } $fields[] = array( 'locator' => 'attributes/' . $key, 'label' => 'Attribute: ' . $name, 'type' => 'json', 'value' => array_map( 'strval', $value ), 'writable' => $can && $simple && $tidy && ! $global && ! $attribute->get_variation(), 'note' => $note, ); } return $fields; } /** The product's term IDs for a taxonomy locator, sorted (the stored order isn't meaningful). */ private static function term_ids( $product, $locator ) { $ids = 'categories' === $locator ? $product->get_category_ids( 'edit' ) : $product->get_tag_ids( 'edit' ); $ids = array_values( array_unique( array_map( 'intval', (array) $ids ) ) ); sort( $ids ); return $ids; } private static function gallery_ids( $product ) { return array_values( array_map( 'intval', (array) $product->get_gallery_image_ids( 'edit' ) ) ); } /** A term as a person reads it: "Parent › Child". */ private static function term_name( $term ) { $names = array(); foreach ( array_reverse( get_ancestors( (int) $term->term_id, $term->taxonomy, 'taxonomy' ) ) as $ancestor ) { $parent = get_term( $ancestor, $term->taxonomy ); if ( $parent instanceof \WP_Term ) { $names[] = $parent->name; } } $names[] = $term->name; return html_entity_decode( implode( ' › ', $names ), ENT_QUOTES, 'UTF-8' ); } /** Term ids as a person reads them: "Dance Shoes (#12), Kids (#15)", or "(none)". */ private static function show_terms( array $ids, $taxonomy ) { $out = array(); foreach ( $ids as $id ) { $term = get_term( (int) $id, $taxonomy ); $out[] = ( $term instanceof \WP_Term ? self::term_name( $term ) : 'deleted' ) . ' (#' . (int) $id . ')'; } return $out ? implode( ', ', $out ) : '(none)'; } /** Attachment ids as a person reads them: "studio.png (#41)", or "(none)". */ private static function show_images( array $ids ) { $out = array(); foreach ( $ids as $id ) { if ( ! $id ) { continue; } $file = (string) get_attached_file( (int) $id ); $out[] = ( '' !== $file ? wp_basename( $file ) : 'missing image' ) . ' (#' . (int) $id . ')'; } return $out ? implode( ', ', $out ) : '(none)'; } /** * Are the product's attribute keys the ones WooCommerce's set_attributes() would give them (sanitize_title of * the name)? Only then does writing one attribute leave the others' keys exactly as they are. */ private static function attributes_tidy( $product ) { $loaded = $product->get_attributes( 'edit' ); foreach ( $loaded as $key => $attribute ) { if ( ! $attribute instanceof \WC_Product_Attribute || sanitize_title( $attribute->get_name() ) !== (string) $key ) { return false; } } // Every stored entry must be one WooCommerce loaded: save() rewrites the list from what it loaded, so an // entry it skips (a global attribute whose taxonomy is gone or unregistered) would be dropped. $stored = get_post_meta( $product->get_id(), self::ATTRIBUTES_META, true ); $stored = is_array( $stored ) ? array_map( 'strval', array_keys( $stored ) ) : array(); $keys = array_map( 'strval', array_keys( $loaded ) ); sort( $stored ); sort( $keys ); return $stored === $keys; } /** A JSON list (0, 1, 2… keys), or a Tool_Error naming the expected shape. */ private static function id_list( $value, $label, $example ) { if ( ! is_array( $value ) || ( $value && array_keys( $value ) !== range( 0, count( $value ) - 1 ) ) ) { throw new Tool_Error( esc_html( "$label takes a list, e.g. $example. Nothing was changed." ) ); } return $value; } /** * Existing term ids of $taxonomy, as a sorted list without duplicates. Names are refused: ADI assigns * existing terms only and never creates new ones. */ private static function terms_value( $value, $locator ) { $taxonomy = self::TAXONOMIES[ $locator ]; $singular = 'categories' === $locator ? 'category' : 'tag'; $label = 'categories' === $locator ? 'Product categories' : 'Product tags'; $ids = array(); foreach ( self::id_list( $value, $label, '[12, 15]' ) as $item ) { if ( is_int( $item ) && $item > 0 ) { $ids[] = $item; } elseif ( is_string( $item ) && ctype_digit( $item ) && (int) $item > 0 ) { $ids[] = (int) $item; } elseif ( is_string( $item ) ) { throw new Tool_Error( esc_html( "\"$item\" isn't a product $singular ID. ADI assigns existing {$singular}s only and doesn't create new ones: add it in WooCommerce → Products first, then use its ID from choices. Nothing was changed." ) ); } else { throw new Tool_Error( esc_html( "$label takes product $singular IDs (whole numbers from choices). Nothing was changed." ) ); } } $ids = array_values( array_unique( $ids ) ); if ( count( $ids ) > self::MAX_TERMS ) { throw new Tool_Error( esc_html( "$label: at most " . self::MAX_TERMS . " per change. Nothing was changed." ) ); } foreach ( $ids as $id ) { $term = get_term( $id ); if ( ! $term instanceof \WP_Term ) { throw new Tool_Error( esc_html( "There is no product $singular #$id (it may have been deleted). Use an ID from choices. Nothing was changed." ) ); } if ( $term->taxonomy !== $taxonomy ) { throw new Tool_Error( esc_html( "#$id isn't a product $singular. Use an ID from choices. Nothing was changed." ) ); } } if ( ! $ids && 'categories' === $locator ) { $default = (int) get_option( 'default_product_cat', 0 ); if ( $default && get_term( $default, $taxonomy ) instanceof \WP_Term ) { $ids = array( $default ); // what WooCommerce saves for a product without categories } } sort( $ids ); return $ids; } /** * A Media Library image the connected user may see, or a Tool_Error. $kept: images the field holds now — those * may stay (or move) without the read check, so an image someone else added isn't forced out. */ private static function image_id( $id, array $kept = array() ) { if ( 'attachment' !== get_post_type( $id ) || ! wp_attachment_is_image( $id ) || 'trash' === get_post_status( $id ) ) { throw new Tool_Error( esc_html( "Media #$id is not an image in this site's Media Library (use wp_search_media). Nothing was changed." ) ); } if ( ! in_array( (int) $id, $kept, true ) && ! current_user_can( 'read_post', $id ) ) { throw new Tool_Error( esc_html( "Media #$id is not an image the connected WordPress user may use. Nothing was changed." ) ); } return $id; } private static function gallery_value( $value, array $kept ) { $ids = array(); foreach ( self::id_list( $value, 'The product gallery', '[41, 42]' ) as $item ) { if ( is_int( $item ) && $item > 0 ) { $ids[] = $item; } elseif ( is_string( $item ) && ctype_digit( $item ) && (int) $item > 0 ) { $ids[] = (int) $item; } else { throw new Tool_Error( 'The product gallery takes Media Library image IDs (use wp_search_media). Nothing was changed.' ); } } $ids = array_values( array_unique( $ids ) ); // as WooCommerce's setter does, keeping the first of each if ( count( $ids ) > self::MAX_GALLERY ) { throw new Tool_Error( esc_html( 'The product gallery holds at most ' . self::MAX_GALLERY . ' images through ADI. Nothing was changed.' ) ); } foreach ( $ids as $id ) { self::image_id( $id, $kept ); } return $ids; } /** An attribute's values: plain text, one per item (WooCommerce stores them joined with "|"). */ private static function attribute_values( $value, $label ) { $out = array(); foreach ( self::id_list( $value, $label, '["Leather", "Canvas"]' ) as $item ) { if ( is_int( $item ) || is_float( $item ) ) { $item = (string) $item; } if ( ! is_string( $item ) ) { throw new Tool_Error( esc_html( "$label takes a list of plain-text values. Nothing was changed." ) ); } $item = trim( $item ); if ( '' === $item ) { throw new Tool_Error( esc_html( "$label: a value can't be empty. Nothing was changed." ) ); } if ( false !== strpos( $item, WC_DELIMITER ) ) { throw new Tool_Error( esc_html( "$label: a value can't contain \"" . WC_DELIMITER . '" (WooCommerce separates values with it); give each value as its own list item. Nothing was changed.' ) ); } if ( wc_clean( $item ) !== $item || html_entity_decode( $item, ENT_QUOTES, 'UTF-8' ) !== $item ) { throw new Tool_Error( esc_html( "$label: values are plain text (no markup, HTML entities, line breaks or repeated spaces). Nothing was changed." ) ); } if ( mb_strlen( $item ) > 200 ) { throw new Tool_Error( esc_html( "$label: a value can be at most 200 characters. Nothing was changed." ) ); } if ( in_array( $item, $out, true ) ) { throw new Tool_Error( esc_html( "$label: \"$item\" is listed twice. Nothing was changed." ) ); } $out[] = $item; } if ( ! $out ) { throw new Tool_Error( esc_html( "$label needs at least one value; ADI doesn't remove attributes (do that in WooCommerce → Products). Nothing was changed." ) ); } if ( count( $out ) > self::MAX_VALUES ) { throw new Tool_Error( esc_html( "$label: at most " . self::MAX_VALUES . ' values. Nothing was changed.' ) ); } return $out; } public function read( \WP_Post $post, $locator ) { if ( preg_match( self::VARIATION_RE, (string) $locator, $m ) ) { $variation = in_array( $m[2], self::VARIATION_PROPS, true ) ? self::variation_of( $post, (int) $m[1] ) : null; if ( ! $variation ) { return null; } foreach ( self::variation_fields( $post, $variation ) as $field ) { if ( $field['locator'] === $locator ) { return $field; } } return null; } // One field is wanted: skip what only the listing needs (term choices, variation summaries). $this->light = 0 !== strpos( (string) $locator, 'variations' ); try { foreach ( $this->list_fields( $post ) as $field ) { if ( $field['locator'] === $locator ) { return $field; } } } finally { $this->light = false; } return null; } /** * The store's rules for a value, checked before any restore point is taken (Content::prepare_update). * Returns the value to write, normalised (prices to the store's decimals, stock to an integer). */ public function validate( \WP_Post $post, $locator, $value ) { $product = self::product( $post ); $cur = self::currency(); if ( preg_match( self::VARIATION_RE, (string) $locator, $m ) ) { // A variation's field: the same rules, against the variation's own values (#22). $product = self::variation_of( $post, (int) $m[1] ); if ( ! $product ) { throw new Tool_Error( esc_html( "#{$m[1]} isn't a variation of #{$post->ID}. Nothing was changed." ) ); } $locator = $m[2]; if ( 'image' === $locator ) { return 0 === $value ? 0 : self::image_id( (int) $value, array( (int) $product->get_image_id( 'edit' ) ) ); } } switch ( $locator ) { case 'regular_price': $price = self::price( $value, 'The regular price' ); if ( '' === $price ) { throw new Tool_Error( 'The regular price can\'t be emptied through ADI (the product could no longer be bought). Nothing was changed.' ); } $sale = (string) $product->get_sale_price( 'edit' ); if ( '' !== $sale && (float) $sale >= (float) $price ) { throw new Tool_Error( esc_html( 'This product is on sale for ' . self::money( $sale ) . "; a regular price of $price $cur would be at or below the sale price. Change or empty the sale price first. Nothing was changed." ) ); } return $price; case 'sale_price': $price = self::price( $value, 'The sale price' ); if ( '' !== $price ) { $regular = (string) $product->get_regular_price( 'edit' ); if ( '' === $regular ) { throw new Tool_Error( 'This product has no regular price, so it can\'t have a sale price. Set the regular price first. Nothing was changed.' ); } if ( (float) $price >= (float) $regular ) { throw new Tool_Error( esc_html( "The sale price must be below the regular price (" . self::money( $regular ) . "); $price $cur isn't. Nothing was changed." ) ); } } return $price; case 'date_on_sale_from': case 'date_on_sale_to': $boundary = 'date_on_sale_from' === $locator ? '00:00:00' : '23:59:59'; $date = self::date( $value, 'date_on_sale_from' === $locator ? 'The sale start date' : 'The sale end date' ); if ( 19 === strlen( $date ) && substr( $date, 11 ) === $boundary ) { $date = substr( $date, 0, 10 ); // the day boundary is what a bare date means: stored and read back the same } $from = 'date_on_sale_from' === $locator ? $date : self::date_value( $product->get_date_on_sale_from( 'edit' ) ); $to = 'date_on_sale_to' === $locator ? $date : self::date_value( $product->get_date_on_sale_to( 'edit' ), '23:59:59' ); // Compared as full times: a bare start date is 00:00:00, a bare end date 23:59:59. $from_t = '' === $from ? '' : ( 10 === strlen( $from ) ? $from . ' 00:00:00' : $from ); $to_t = '' === $to ? '' : ( 10 === strlen( $to ) ? $to . ' 23:59:59' : $to ); if ( '' !== $from_t && '' !== $to_t && $from_t > $to_t ) { throw new Tool_Error( esc_html( "The sale would end ($to) before it starts ($from). Nothing was changed." ) ); } return $date; case 'sku': if ( wc_clean( $value ) !== $value ) { throw new Tool_Error( 'A SKU is plain text (no markup or control characters). Nothing was changed.' ); } if ( '' !== $value && ! wc_product_has_unique_sku( $product->get_id(), $value ) ) { throw new Tool_Error( esc_html( "The SKU \"$value\" is already used by another product or variation; SKUs must be unique. Nothing was changed." ) ); } return $value; case 'stock_quantity': if ( ! is_int( $value ) && ! ( is_float( $value ) && floor( $value ) === $value ) ) { throw new Tool_Error( 'The stock quantity is a whole number of units. Nothing was changed.' ); } if ( abs( $value ) > 1000000000 ) { throw new Tool_Error( 'That stock quantity is out of range. Nothing was changed.' ); } return (int) $value; case 'categories': case 'tags': return self::terms_value( $value, $locator ); case 'featured_image': return 0 === $value ? 0 : self::image_id( (int) $value, array( (int) $product->get_image_id( 'edit' ) ) ); case 'gallery': return self::gallery_value( $value, self::gallery_ids( $product ) ); } if ( 0 === strpos( $locator, 'attributes/' ) ) { return self::attribute_values( $value, 'The attribute "' . wc_attribute_label( substr( $locator, 11 ), $product ) . '"' ); } return $value; } /** * A price exactly as written: digits with at most one decimal point (the store's own decimal * separator is accepted too), no sign, currency symbol, thousands separator or exponent, and no * more significant decimals than the store shows. Returned in WooCommerce's stored form * (wc_format_decimal, padded to the store's decimals); '' stays ''. */ private static function price( $value, $label ) { $v = trim( (string) $value ); if ( '' === $v ) { return ''; } if ( preg_match( '/^-\s*[\d.,]/', $v ) ) { throw new Tool_Error( esc_html( "$label can't be negative. Nothing was changed." ) ); } $sep = (string) wc_get_price_decimal_separator(); if ( '' !== $sep && '.' !== $sep && 1 === strlen( $sep ) && false === strpos( $v, '.' ) ) { if ( preg_match( '/^\d{1,3}' . preg_quote( $sep, '/' ) . '\d{3}$/', $v ) ) { // "1,000" in a comma-decimal store: one thousand, or one with three decimals? Don't guess with money. throw new Tool_Error( esc_html( "$label \"$v\" is ambiguous (thousands separator or decimals?). Write it with a point and no thousands separator, e.g. 1000.00. Nothing was changed." ) ); } $v = str_replace( $sep, '.', $v ); } if ( ! preg_match( '/^(\d+)(?:\.(\d+))?$/', $v, $m ) ) { throw new Tool_Error( esc_html( "$label takes an amount like 49.99: digits and one decimal point, without a currency sign, thousands separator or exponent. Nothing was changed." ) ); } if ( strlen( ltrim( $m[1], '0' ) ) > 12 ) { throw new Tool_Error( esc_html( "$label is too large for WooCommerce to store exactly. Nothing was changed." ) ); } $dp = (int) wc_get_price_decimals(); $decimal = isset( $m[2] ) ? rtrim( $m[2], '0' ) : ''; if ( strlen( $decimal ) > $dp ) { throw new Tool_Error( esc_html( "$label has more decimals than this store uses ($dp); WooCommerce would round it. Nothing was changed." ) ); } $int = ltrim( $m[1], '0' ); if ( 0 === $dp && '' === $int && 'The sale price' === $label ) { // Stored as "0", which WooCommerce's sale handling reads as "no sale". throw new Tool_Error( 'A sale price of 0 can\'t be scheduled reliably in a store without decimals. Nothing was changed.' ); } $out = (string) wc_format_decimal( ( '' === $int ? '0' : $int ) . ( '' !== $decimal ? '.' . $decimal : '' ), $dp ); if ( '' === $out || ! is_numeric( $out ) || (float) $out < 0 ) { throw new Tool_Error( esc_html( "$label isn't a valid amount. Nothing was changed." ) ); } return $out; } /** A calendar date YYYY-MM-DD (or, as read back for a date set elsewhere, YYYY-MM-DD HH:MM:SS), or '' to clear. */ private static function date( $value, $label ) { $v = trim( (string) $value ); if ( '' === $v ) { return ''; } if ( ! preg_match( '/^(\d{4})-(\d{2})-(\d{2})(?: ([01]\d|2[0-3]):[0-5]\d:[0-5]\d)?$/', $v, $m ) || ! checkdate( (int) $m[2], (int) $m[3], (int) $m[1] ) ) { throw new Tool_Error( esc_html( "$label takes a real date as YYYY-MM-DD (in the site's timezone), or empty to remove it. Nothing was changed." ) ); } return $v; } public function write( \WP_Post $post, $locator, $value ) { $product = self::product( $post ); $variation = null; if ( preg_match( self::VARIATION_RE, (string) $locator, $m ) ) { $variation = in_array( $m[2], self::VARIATION_PROPS, true ) ? self::variation_of( $post, (int) $m[1] ) : null; if ( ! $variation ) { throw new Tool_Error( esc_html( "woocommerce:$locator can't be changed through ADI." ) ); } $product = $variation; $locator = $m[2]; } try { switch ( $locator ) { case 'enabled': if ( ! $variation ) { throw new Tool_Error( esc_html( "woocommerce:$locator can't be changed through ADI." ) ); } $product->set_status( $value ? 'publish' : 'private' ); // wp-admin's "Enabled" checkbox break; case 'image': if ( ! $variation ) { throw new Tool_Error( esc_html( "woocommerce:$locator can't be changed through ADI." ) ); } $product->set_image_id( (int) $value ? (int) $value : '' ); break; case 'regular_price': $product->set_regular_price( (string) $value ); break; case 'sale_price': $product->set_sale_price( (string) $value ); break; case 'date_on_sale_from': // As wp-admin does: a sale starts at the beginning of its first day… $product->set_date_on_sale_from( '' === (string) $value ? '' : ( 10 === strlen( $value ) ? $value . ' 00:00:00' : $value ) ); break; case 'date_on_sale_to': // …and ends at the end of its last day (site timezone). $product->set_date_on_sale_to( '' === (string) $value ? '' : ( 10 === strlen( $value ) ? $value . ' 23:59:59' : $value ) ); break; case 'sku': $product->set_sku( (string) $value ); break; case 'manage_stock': $product->set_manage_stock( (bool) $value ); break; case 'stock_quantity': $product->set_stock_quantity( null === $value || '' === $value ? '' : (int) $value ); break; case 'stock_status': $product->set_stock_status( (string) $value ); break; case 'categories': $product->set_category_ids( array_map( 'intval', (array) $value ) ); break; case 'tags': $product->set_tag_ids( array_map( 'intval', (array) $value ) ); break; case 'featured_image': $product->set_image_id( (int) $value ? (int) $value : '' ); break; case 'gallery': $product->set_gallery_image_ids( array_map( 'intval', (array) $value ) ); break; default: if ( 0 !== strpos( $locator, 'attributes/' ) ) { throw new Tool_Error( esc_html( "woocommerce:$locator can't be changed through ADI." ) ); } $this->write_attribute( $product, substr( $locator, 11 ), $value ); } $product->save(); if ( $variation ) { // As wp-admin does after saving variations: the parent's price range, stock status and caches follow. \WC_Product_Variable::sync( $post->ID ); wc_delete_product_transients( $post->ID ); } } catch ( \WC_Data_Exception $e ) { throw new Tool_Error( esc_html( 'WooCommerce refused the change: ' . wp_strip_all_tags( $e->getMessage() ) . ' Nothing was changed.' ) ); } } /** * New values for one local attribute: the product's own WC_Product_Attribute objects, that one cloned with * set_options(), all handed back to set_attributes() (which keys them by name — attributes_tidy() made sure * that is how they are keyed now). save() follows in write(). */ private function write_attribute( $product, $key, $value ) { $attributes = $product->get_attributes( 'edit' ); if ( ! isset( $attributes[ $key ] ) || ! $attributes[ $key ] instanceof \WC_Product_Attribute || $attributes[ $key ]->is_taxonomy() || $attributes[ $key ]->get_variation() || ! self::attributes_tidy( $product ) ) { throw new Tool_Error( esc_html( "woocommerce:attributes/$key can't be changed through ADI." ) ); } $attribute = clone $attributes[ $key ]; $attribute->set_options( array_values( array_map( 'strval', (array) $value ) ) ); $attributes[ $key ] = $attribute; $product->set_attributes( array_values( $attributes ) ); } // ── Restore points (#15) ──────────────────────────────────────────────────────────── /** * May a restore put back product meta $key (of a simple product)? $stock: the restore point was taken for * a stock change. $prices: price writing is on (else price meta stays as it is, like a direct write). */ public static function restorable( $key, $stock, $prices = true ) { if ( in_array( $key, self::PRICE_META, true ) ) { return (bool) $prices; } return in_array( $key, self::META, true ) || ( $stock && in_array( $key, self::STOCK_META, true ) ); } /** Was a restore point with this recorded path taken for a stock change? */ public static function is_stock_path( $path ) { foreach ( self::STOCK_FIELDS as $field ) { if ( 'woocommerce:' . $field === $path ) { return true; } } // A variation's stock field (#22). return (bool) preg_match( '#^woocommerce:variations/\d+/(' . implode( '|', self::STOCK_FIELDS ) . ')\z#', (string) $path ); } /** May a restore put image $id back (#21/#22)? An image in the Media Library, not in the trash — what a write accepts. */ public static function usable_image( $id ) { return 'attachment' === get_post_type( (int) $id ) && wp_attachment_is_image( (int) $id ) && 'trash' !== get_post_status( (int) $id ); } /** Is $id a variable or grouped product (prices and stock status synced from its children)? */ public static function synced_product( $id ) { if ( 'product' !== get_post_type( (int) $id ) || ! function_exists( 'wc_get_product' ) ) { return false; } $product = wc_get_product( (int) $id ); return $product && $product->is_type( array( 'variable', 'grouped' ) ); } /** Is $id a variation of the product $parent (now)? */ public static function is_child( $id, $parent ) { return 'product_variation' === get_post_type( (int) $id ) && (int) wp_get_post_parent_id( (int) $id ) === (int) $parent; } /** * Variations a restore point of $target records (#22): the one a variation field's path names. A point taken * for anything else records none, and its restore leaves the variations as they are. */ public static function snapshot_children( $children, $target, $path ) { if ( is_int( $target ) && is_string( $path ) && preg_match( '#^woocommerce:variations/(\d+)/#', $path, $m ) && self::is_child( (int) $m[1], $target ) ) { $children[] = (int) $m[1]; } return $children; } /** * May a restore put back variation meta $key? What the adapter writes on a variation, as for a simple product * (restorable()): price meta while price writing is on, the SKU, the variation image, and stock meta only from * a stock change's point. Never `_price` (derived: recomputed after the restore). */ public static function restorable_child( $key, $stock, $prices ) { return '_thumbnail_id' === $key || self::restorable( $key, $stock, $prices ); } /** * Before a restore changes anything: a SKU recorded in the point that another product or variation * uses now can't come back (SKUs are unique). * * @param \WP_Post $post * @param array $row * @param array $meta key => recorded values (empty when an older caller doesn't pass it) * @param array $children variation id => { status, meta: key => recorded values } (#22) */ public static function check_restore( $post, $row, $meta = array(), $children = array() ) { if ( ! $post instanceof \WP_Post ) { return; } // Variations the point records (#22): a SKU another product took since, and enabling one, which publishes it. $type = get_post_type_object( 'product' ); foreach ( (array) $children as $child => $recorded ) { $child = (int) $child; if ( ! self::is_child( $child, $post->ID ) || ! is_array( $recorded ) || ! in_array( get_post_status( $child ), array( 'publish', 'private' ), true ) ) { continue; } $status = isset( $recorded['status'] ) ? (string) $recorded['status'] : ''; $child_meta = isset( $recorded['meta'] ) && is_array( $recorded['meta'] ) ? $recorded['meta'] : array(); if ( 'publish' === $status && 'publish' !== get_post_status( $child ) && ( ! $type || ! current_user_can( $type->cap->publish_posts ) ) ) { throw new Tool_Error( esc_html( "That restore point enables variation #$child, and the connected WordPress user may not publish products. Nothing was changed." ) ); } if ( isset( $child_meta['_sku'] ) && function_exists( 'wc_product_has_unique_sku' ) ) { $sku = (string) end( $child_meta['_sku'] ); if ( '' !== $sku && (string) get_post_meta( $child, '_sku', true ) !== $sku && ! wc_product_has_unique_sku( $child, $sku ) ) { throw new Tool_Error( esc_html( "That restore point gives variation #$child the SKU \"$sku\", which another product or variation uses now. Nothing was changed." ) ); } } if ( isset( $child_meta['_thumbnail_id'] ) ) { $image = (int) end( $child_meta['_thumbnail_id'] ); // (An image gone since is left out by Snapshots::restore_children(), not refused.) if ( $image && (int) get_post_meta( $child, '_thumbnail_id', true ) !== $image && self::usable_image( $image ) && ! current_user_can( 'read_post', $image ) ) { throw new Tool_Error( esc_html( "That restore point puts image #$image back on variation #$child, and the connected WordPress user may not use it. Nothing was changed." ) ); } } } if ( self::catalog_product( $post->ID ) ) { // Images the restore would put back must still be ones the connected user may use (as for a write). $images = static function ( $thumb, $gallery ) { return array_filter( array_merge( wp_parse_id_list( (string) $thumb ), wp_parse_id_list( (string) $gallery ) ) ); }; $then = $images( isset( $meta['_thumbnail_id'] ) ? end( $meta['_thumbnail_id'] ) : '', isset( $meta['_product_image_gallery'] ) ? end( $meta['_product_image_gallery'] ) : '' ); $now = $images( get_post_meta( $post->ID, '_thumbnail_id', true ), get_post_meta( $post->ID, '_product_image_gallery', true ) ); foreach ( array_diff( $then, $now ) as $image ) { // (Images deleted, trashed or no longer images since are left out by restore_images(), not refused.) if ( 'attachment' === get_post_type( $image ) && wp_attachment_is_image( $image ) && 'trash' !== get_post_status( $image ) && ! current_user_can( 'read_post', $image ) ) { throw new Tool_Error( esc_html( "That restore point puts image #$image back on #{$post->ID}, and the connected WordPress user may not use it. Nothing was changed." ) ); } } } if ( ! self::restorable_product( $post->ID ) || ! function_exists( 'wc_product_has_unique_sku' ) || ! isset( $meta['_sku'] ) ) { return; } $sku = (string) end( $meta['_sku'] ); if ( '' !== $sku && (string) get_post_meta( $post->ID, '_sku', true ) !== $sku && ! wc_product_has_unique_sku( $post->ID, $sku ) ) { throw new Tool_Error( esc_html( "That restore point gives #{$post->ID} the SKU \"$sku\", which another product or variation uses now. Nothing was changed." ) ); } } /** * The product's attribute list for a restore (#15 allowlist): of the recorded `_product_attributes`, only the * values of local, non-variation attributes that exist both then and now go back — what the adapter writes. * Global attributes, variation flags, names, positions, visibility and attributes added or removed since stay * as they are now. Simple products only ($ctx['product']). * * @param array $want key => recorded values (decoded) the restore would write. * @param array $now key => values stored now. */ public static function restore_meta( $want, $now, $id, $ctx ) { if ( ! is_array( $want ) ) { return $want; } if ( ! empty( $ctx['catalog'] ) ) { $want = self::restore_images( $want, $now, (int) $id ); } $key = self::ATTRIBUTES_META; if ( empty( $ctx['product'] ) ) { return $want; } $cur = isset( $now[ $key ] ) && 1 === count( $now[ $key ] ) ? $now[ $key ][0] : null; if ( null === $cur ) { // None now (or stored oddly): attributes aren't added or removed by a restore. if ( isset( $now[ $key ] ) ) { $want[ $key ] = $now[ $key ]; } else { unset( $want[ $key ] ); } return $want; } $rec = isset( $want[ $key ] ) && 1 === count( $want[ $key ] ) ? $want[ $key ][0] : null; $want[ $key ] = array( null === $rec ? $cur : self::merge_attributes( $rec, $cur ) ); return $want; } /** Images a restore couldn't put back (deleted, trashed or no longer images since): post id => labels. */ private static $gone_images = array(); /** * Images of a catalog product a restore puts back must be what a write accepts: an image in the Media Library, * not in the trash (one the user can't read refuses the whole restore, check_restore()). Others are left out — * the gallery without them, the product image as it is now — and reported (label_restore()). */ private static function restore_images( array $want, array $now, $id ) { $usable = static function ( $image ) { return 'attachment' === get_post_type( $image ) && wp_attachment_is_image( $image ) && 'trash' !== get_post_status( $image ); }; $current = array_merge( isset( $now['_thumbnail_id'] ) ? wp_parse_id_list( (string) end( $now['_thumbnail_id'] ) ) : array(), isset( $now['_product_image_gallery'] ) ? wp_parse_id_list( (string) end( $now['_product_image_gallery'] ) ) : array() ); $gone = array(); if ( isset( $want['_product_image_gallery'] ) && 1 === count( $want['_product_image_gallery'] ) ) { $keep = array(); foreach ( wp_parse_id_list( (string) $want['_product_image_gallery'][0] ) as $image ) { if ( in_array( $image, $current, true ) || $usable( $image ) ) { $keep[] = $image; } elseif ( $image ) { $gone[] = "image #$image"; } } $want['_product_image_gallery'] = array( implode( ',', $keep ) ); } if ( isset( $want['_thumbnail_id'] ) && 1 === count( $want['_thumbnail_id'] ) ) { $image = (int) $want['_thumbnail_id'][0]; if ( $image && ! in_array( $image, $current, true ) && ! $usable( $image ) ) { $gone[] = "image #$image"; if ( isset( $now['_thumbnail_id'] ) ) { $want['_thumbnail_id'] = $now['_thumbnail_id']; } else { unset( $want['_thumbnail_id'] ); } } } if ( $gone ) { self::$gone_images[ $id ] = array_values( array_unique( $gone ) ); } else { unset( self::$gone_images[ $id ] ); } return $want; } /** Stored `_product_attributes` as an array, or null (never objects). */ private static function attributes_array( $raw ) { if ( ! is_string( $raw ) || ! is_serialized( $raw ) ) { return null; } $value = unserialize( trim( $raw ), array( 'allowed_classes' => false ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- stored meta, objects refused return is_array( $value ) ? $value : null; } /** $current with the recorded values of the local attributes both have (see restore_meta()). */ public static function merge_attributes( $recorded, $current ) { $rec = self::attributes_array( $recorded ); $now = self::attributes_array( $current ); if ( null === $rec || null === $now ) { return $current; } $local = static function ( $a ) { return is_array( $a ) && empty( $a['is_taxonomy'] ) && empty( $a['is_variation'] ); }; $out = $now; foreach ( $now as $k => $a ) { if ( $local( $a ) && isset( $rec[ $k ] ) && $local( $rec[ $k ] ) && isset( $rec[ $k ]['value'] ) && is_string( $rec[ $k ]['value'] ) ) { $out[ $k ]['value'] = $rec[ $k ]['value']; } } return $out === $now ? $current : serialize( $out ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- the form update_post_meta stores } /** What a restore can change that matters to the shop: prices, sale window, stock — and the catalog data (#21). */ private static function shop_state( $product ) { $attributes = array(); foreach ( $product->get_attributes( 'edit' ) as $attribute ) { if ( $attribute instanceof \WC_Product_Attribute && ! $attribute->is_taxonomy() && ! $attribute->get_variation() ) { $attributes[] = $attribute->get_name() . ': ' . implode( ', ', $attribute->get_options() ); } } return array( 'regular_price' => (string) $product->get_regular_price( 'edit' ), 'sale_price' => (string) $product->get_sale_price( 'edit' ), 'date_on_sale_from' => self::date_value( $product->get_date_on_sale_from( 'edit' ) ), 'date_on_sale_to' => self::date_value( $product->get_date_on_sale_to( 'edit' ), '23:59:59' ), 'stock_quantity' => null === $product->get_stock_quantity( 'edit' ) ? '' : (string) (int) $product->get_stock_quantity( 'edit' ), 'stock_status' => (string) $product->get_stock_status( 'edit' ), 'categories' => self::show_terms( self::term_ids( $product, 'categories' ), 'product_cat' ), 'tags' => self::show_terms( self::term_ids( $product, 'tags' ), 'product_tag' ), 'featured_image' => self::show_images( array( (int) $product->get_image_id( 'edit' ) ) ), 'gallery' => self::show_images( self::gallery_ids( $product ) ), 'attributes' => $attributes ? implode( '; ', $attributes ) : '(none)', ); } /** Restore-result keys that are catalog data (#21), not prices or stock. */ const CATALOG_STATE = array( 'categories', 'tags', 'featured_image', 'gallery', 'attributes' ); /** Before a restore (or roll-back): note the product's shop state, to re-sync what changed and report it. */ public static function before_restore( $target, $children = array() ) { if ( is_int( $target ) && 'product' === get_post_type( $target ) && function_exists( 'wc_get_product' ) ) { $product = wc_get_product( $target ); if ( $product ) { self::$restoring[ $target ] = self::shop_state( $product ); } self::$restoring_children[ $target ] = array(); foreach ( (array) $children as $child ) { $variation = self::is_child( (int) $child, $target ) ? wc_get_product( (int) $child ) : null; if ( $variation ) { self::$restoring_children[ $target ][ (int) $child ] = self::variation_state( $variation ); } } } } /** What a restore can change on a variation (#22), as a person reads it. */ private static function variation_state( $variation ) { $qty = $variation->get_stock_quantity( 'edit' ); return array( 'regular_price' => (string) $variation->get_regular_price( 'edit' ), 'sale_price' => (string) $variation->get_sale_price( 'edit' ), 'date_on_sale_from' => self::date_value( $variation->get_date_on_sale_from( 'edit' ) ), 'date_on_sale_to' => self::date_value( $variation->get_date_on_sale_to( 'edit' ), '23:59:59' ), 'sku' => (string) $variation->get_sku( 'edit' ), 'stock_quantity' => null === $qty || '' === $qty ? '' : (string) (int) $qty, 'stock_status' => (string) $variation->get_stock_status( 'edit' ), 'enabled' => 'publish' === $variation->get_status( 'edit' ) ? 'enabled' : 'disabled', 'image' => self::show_images( array( (int) $variation->get_image_id( 'edit' ) ) ), ); } /** * The active price `_price` of a simple product or variation whose prices or sale window a restore changed, * as WC_Product_Data_Store_CPT::handle_updated_props() computes it, and its scheduled sale events. Not save(): * that would also move post_modified, and a roll-back must leave the row exactly as recorded. */ private static function resync_price( $id, $product ) { $price = $product->is_on_sale( 'edit' ) ? $product->get_sale_price( 'edit' ) : $product->get_regular_price( 'edit' ); if ( (string) get_post_meta( $id, '_price', true ) !== (string) $price ) { update_post_meta( $id, '_price', wc_clean( (string) $price ) ); clean_post_cache( $id ); $product = wc_get_product( $id ); } if ( function_exists( 'wc_maybe_schedule_product_sale_events' ) ) { wc_maybe_schedule_product_sale_events( $id, $product ); // the sale starts/ends at the restored times } return $product; } /** "Hide out of stock items" reads the product_visibility term WooCommerce sets on save() (products and variations). */ private static function sync_visibility( $id, $product ) { if ( ! taxonomy_exists( 'product_visibility' ) ) { return; } if ( 'outofstock' === $product->get_stock_status( 'edit' ) ) { wp_set_object_terms( $id, 'outofstock', 'product_visibility', true ); } else { wp_remove_object_terms( $id, 'outofstock', 'product_visibility' ); } } /** After a restore put variations back (#22): their derived data, then the parent's price range and stock status. */ private static function after_restore_children( $id ) { $children = isset( self::$restoring_children[ $id ] ) ? self::$restoring_children[ $id ] : array(); if ( ! $children ) { return; } $pricing = array( 'regular_price', 'sale_price', 'date_on_sale_from', 'date_on_sale_to' ); $store = \WC_Data_Store::load( 'product' ); foreach ( $children as $child => $was ) { clean_post_cache( $child ); wp_cache_delete( $child, 'post_meta' ); $variation = self::is_child( $child, $id ) ? wc_get_product( $child ) : null; if ( ! $variation ) { continue; } $now = self::variation_state( $variation ); if ( array_intersect_key( $was, array_flip( $pricing ) ) !== array_intersect_key( $now, array_flip( $pricing ) ) ) { $variation = self::resync_price( $child, $variation ); } self::sync_visibility( $child, $variation ); // before the parent sync, which reads which variations are visible if ( method_exists( 'WC_Product_Data_Store_CPT', 'refresh_product_lookup_table' ) ) { $store->refresh_product_lookup_table( $child ); } wc_delete_product_transients( $child ); } \WC_Product_Variable::sync( $id ); clean_post_cache( $id ); wp_cache_delete( $id, 'post_meta' ); } /** * After a restore or roll-back of a product: the restored meta went back row by row, past * WooCommerce's own hooks, so bring its derived data in line. When the restore changed the price or * sale window: the active price `_price` (as WooCommerce's data store computes it) and the scheduled * sale start/end events. Always: the product lookup table, the out-of-stock catalog flag and the * product transients. (The put-back of a refused field write goes through save(), which does all this.) */ public static function after_restore( $id ) { $id = (int) $id; if ( ! $id || 'product' !== get_post_type( $id ) || ! function_exists( 'wc_get_product' ) ) { return; } clean_post_cache( $id ); wp_cache_delete( $id, 'post_meta' ); $product = wc_get_product( $id ); if ( ! $product ) { return; } if ( $product->is_type( 'variable' ) ) { self::after_restore_children( $id ); $product = wc_get_product( $id ); } $was = isset( self::$restoring[ $id ] ) ? self::$restoring[ $id ] : null; $now = self::shop_state( $product ); $pricing = array( 'regular_price', 'sale_price', 'date_on_sale_from', 'date_on_sale_to' ); $moved = null !== $was && array_intersect_key( $was, array_flip( $pricing ) ) !== array_intersect_key( $now, array_flip( $pricing ) ); if ( $moved && ! $product->is_type( array( 'variable', 'grouped' ) ) ) { $product = self::resync_price( $id, $product ); } self::sync_visibility( $id, $product ); $store = \WC_Data_Store::load( 'product' ); if ( method_exists( 'WC_Product_Data_Store_CPT', 'refresh_product_lookup_table' ) ) { $store->refresh_product_lookup_table( $id ); } // Categories or tags put back (Snapshots, wp_set_object_terms): WooCommerce's own per-term product counts. if ( null !== $was && ( $was['categories'] !== $now['categories'] || $was['tags'] !== $now['tags'] ) && function_exists( '_wc_recount_terms_by_product' ) ) { _wc_recount_terms_by_product( $id ); } wc_delete_product_transients( $id ); } /** * Write results: each WooCommerce price change carries the store currency and its before → after * as a person reads it ("$49.99 CAD → $44.99 CAD"), for ADI's approval history. */ public static function label_result( $result ) { if ( is_array( $result ) && isset( $result['restored'] ) && is_int( $result['restored'] ) && isset( self::$restoring[ $result['restored'] ] ) ) { return self::label_restore( $result ); } if ( ! is_array( $result ) || empty( $result['changes'] ) || ! is_array( $result['changes'] ) || ! function_exists( 'get_woocommerce_currency' ) ) { return $result; } $shown = array(); foreach ( $result['changes'] as $i => $change ) { if ( ! is_array( $change ) || ! isset( $change['path'] ) || ! is_string( $change['path'] ) ) { continue; } // A variation's field (#22): labelled with the variation's attributes, otherwise like the product's own. $path = $change['path']; $prefix = ''; if ( preg_match( '#^woocommerce:variations/(\d+)/([a-z_]+)\z#', $path, $m ) ) { $variation = wc_get_product( (int) $m[1] ); $prefix = 'Variation ' . ( $variation ? self::variation_name( $variation ) : '#' . (int) $m[1] ) . ' — '; $path = 'woocommerce:' . $m[2]; } $catalog = self::show_catalog( array_merge( $change, array( 'path' => $path ) ), isset( $result['id'] ) ? $result['id'] : 0 ); if ( null !== $catalog ) { $result['changes'][ $i ]['shown'] = $catalog[1]; $shown[] = $prefix . $catalog[0] . ': ' . $catalog[1]; continue; } if ( in_array( $path, array( 'woocommerce:date_on_sale_from', 'woocommerce:date_on_sale_to' ), true ) ) { $result['changes'][ $i ]['currency'] = self::currency(); continue; } if ( ! in_array( $path, array( 'woocommerce:regular_price', 'woocommerce:sale_price' ), true ) ) { continue; } $label = 'woocommerce:regular_price' === $path ? 'Regular price' : 'Sale price'; $result['changes'][ $i ]['currency'] = self::currency(); $result['changes'][ $i ]['shown'] = self::money( $change['before'] ) . ' → ' . self::money( $change['after'] ); $shown[] = $prefix . "$label: " . $result['changes'][ $i ]['shown']; } if ( $shown && isset( $result['message'] ) && is_string( $result['message'] ) ) { $result['message'] .= ' ' . implode( '; ', $shown ) . '.'; } return $result; } /** * A catalog change (#21) as a person reads it: array( label, "before → after" ) with term names, image * file names and attribute values; null for any other change. */ private static function show_catalog( array $change, $id = 0 ) { $path = $change['path']; $before = isset( $change['before'] ) ? $change['before'] : null; $after = isset( $change['after'] ) ? $change['after'] : null; $list = static function ( $v ) { return array_map( 'intval', is_array( $v ) ? $v : ( $v ? array( $v ) : array() ) ); }; switch ( $path ) { case 'woocommerce:categories': case 'woocommerce:tags': $tax = 'woocommerce:categories' === $path ? 'product_cat' : 'product_tag'; return array( 'woocommerce:categories' === $path ? 'Categories' : 'Tags', self::show_terms( $list( $before ), $tax ) . ' → ' . self::show_terms( $list( $after ), $tax ) ); case 'woocommerce:featured_image': return array( 'Product image', self::show_images( $list( $before ) ) . ' → ' . self::show_images( $list( $after ) ) ); case 'woocommerce:image': return array( 'Image', self::show_images( $list( $before ) ) . ' → ' . self::show_images( $list( $after ) ) ); case 'woocommerce:enabled': return array( 'Enabled', ( $before ? 'enabled' : 'disabled' ) . ' → ' . ( $after ? 'enabled' : 'disabled' ) ); case 'woocommerce:gallery': return array( 'Gallery', self::show_images( $list( $before ) ) . ' → ' . self::show_images( $list( $after ) ) ); } if ( 0 === strpos( $path, 'woocommerce:attributes/' ) ) { $show = static function ( $v ) { return is_array( $v ) && $v ? implode( ', ', array_map( 'strval', $v ) ) : '(none)'; }; $key = substr( $path, strlen( 'woocommerce:attributes/' ) ); $product = is_numeric( $id ) && (int) $id > 0 ? wc_get_product( (int) $id ) : null; $attrs = $product ? $product->get_attributes( 'edit' ) : array(); $name = isset( $attrs[ $key ] ) && $attrs[ $key ] instanceof \WC_Product_Attribute ? wc_attribute_label( $attrs[ $key ]->get_name(), $product ) : $key; return array( 'Attribute ' . $name, $show( $before ) . ' → ' . $show( $after ) ); } return null; } /** A restore result: the prices, sale dates and stock it changed, before → after (prices in the store currency). */ private static function label_restore( array $result ) { $id = $result['restored']; $was = self::$restoring[ $id ]; unset( self::$restoring[ $id ] ); $product = wc_get_product( $id ); if ( ! $product ) { return $result; } $now = self::shop_state( $product ); $labels = array( 'regular_price' => 'Regular price', 'sale_price' => 'Sale price', 'date_on_sale_from' => 'Sale starts', 'date_on_sale_to' => 'Sale ends', 'stock_quantity' => 'Stock quantity', 'stock_status' => 'Stock status', 'categories' => 'Categories', 'tags' => 'Tags', 'featured_image' => 'Product image', 'gallery' => 'Gallery', 'attributes' => 'Attributes', ); $shop = array(); foreach ( $labels as $key => $label ) { if ( $was[ $key ] === $now[ $key ] ) { continue; } $money = in_array( $key, array( 'regular_price', 'sale_price' ), true ); $show = static function ( $v ) use ( $money ) { return $money ? self::money( $v ) : ( '' === $v ? '(none)' : $v ); }; $shop[ $key ] = array( 'before' => $was[ $key ], 'after' => $now[ $key ], 'shown' => $show( $was[ $key ] ) . ' → ' . $show( $now[ $key ] ) ); $result['message'] .= " $label: " . $shop[ $key ]['shown'] . '.'; } if ( isset( $shop['stock_quantity'] ) ) { $result['message'] .= ' Stock was set back to the restore point\'s count; orders placed since it was taken are not counted in it.'; } // Variations the restore put back (#22), each prefixed with its attributes. $children = isset( self::$restoring_children[ $id ] ) ? self::$restoring_children[ $id ] : array(); unset( self::$restoring_children[ $id ] ); $var_labels = array( 'regular_price' => 'Regular price', 'sale_price' => 'Sale price', 'date_on_sale_from' => 'Sale starts', 'date_on_sale_to' => 'Sale ends', 'sku' => 'SKU', 'stock_quantity' => 'Stock quantity', 'stock_status' => 'Stock status', 'enabled' => 'Enabled', 'image' => 'Image', ); $variations = array(); foreach ( $children as $child => $before ) { $variation = wc_get_product( $child ); if ( ! $variation ) { continue; } $after = self::variation_state( $variation ); foreach ( $var_labels as $key => $label ) { if ( $before[ $key ] === $after[ $key ] ) { continue; } $money = in_array( $key, array( 'regular_price', 'sale_price' ), true ); $show = static function ( $v ) use ( $money ) { return $money ? self::money( $v ) : ( '' === $v ? '(none)' : $v ); }; $variations[ $child ][ $key ] = array( 'before' => $before[ $key ], 'after' => $after[ $key ], 'shown' => $show( $before[ $key ] ) . ' → ' . $show( $after[ $key ] ) ); $result['message'] .= ' Variation ' . self::variation_name( $variation ) . " — $label: " . $variations[ $child ][ $key ]['shown'] . '.'; if ( 'stock_quantity' === $key ) { $result['message'] .= ' Stock was set back to the restore point\'s count; orders placed since it was taken are not counted in it.'; } } } if ( $variations ) { $result['variations'] = $variations; $result['currency'] = self::currency(); } // Images left out: the product's (restore_images()) and its variations' (Snapshots::restore_children()). $missing = array_values( array_unique( array_merge( isset( $result['missing_images'] ) ? (array) $result['missing_images'] : array(), isset( self::$gone_images[ $id ] ) ? self::$gone_images[ $id ] : array() ) ) ); unset( self::$gone_images[ $id ] ); if ( $missing ) { $result['message'] .= ' Not put back, no longer images in the Media Library: ' . implode( ', ', $missing ) . '.'; $result['missing_images'] = $missing; } $catalog = array_intersect_key( $shop, array_flip( self::CATALOG_STATE ) ); $shop = array_diff_key( $shop, $catalog ); if ( $shop ) { $result['prices'] = $shop; $result['currency'] = self::currency(); } if ( $catalog ) { $result['catalog'] = $catalog; } return $result; } }