*/ private $fields = array(); /** * Product id => fingerprint key => the last value read before a save * that was not the form's own: it changed after the form was opened. * * @var array> */ private $newer = array(); /** * @param GuardedField[]|null $fields Fields kept after the save; the * product's tags, categories and SEO * fields when omitted. */ public function __construct( ?array $fields = null ) { foreach ( $fields ?? self::defaultFields() as $field ) { $this->fields[ $field->key() ] = $field; } } /** * Register the guard's hooks. * * @return void */ public static function init(): void { $guard = new self(); add_action( 'edit_form_top', array( $guard, 'renderFingerprints' ) ); add_filter( 'wp_insert_post_data', array( $guard, 'keepNewerText' ), 99, 2 ); add_action( 'woocommerce_admin_process_product_object', array( $guard, 'keepNewerPrice' ) ); add_action( 'pre_post_update', array( $guard, 'readNewerValues' ), 10, 1 ); add_action( 'wp_after_insert_post', array( $guard, 'putBackNewerValues' ), 9, 1 ); } /** * `edit_form_top`: print the load-time fingerprints into the product form. * * @param mixed $post The post being edited. * @return void */ public function renderFingerprints( $post ): void { if ( ! $post instanceof WP_Post || 'product' !== $post->post_type ) { return; } $post_id = (int) $post->ID; $prints = array( 'post_id' => (string) $post_id ); foreach ( self::TEXT_FIELDS as $field ) { $prints[ $field ] = self::textFingerprint( (string) get_post_field( $field, $post_id, 'raw' ) ); } $prints[ self::PRICE_KEY ] = self::priceFingerprint( (string) get_post_meta( $post_id, '_regular_price', true ) ); foreach ( $this->fields as $key => $field ) { $value = $field->read( $post_id ); if ( null !== $value ) { $prints[ $key ] = $field->fingerprint( $value ); } } foreach ( $prints as $key => $value ) { printf( '', esc_attr( self::FIELD ), esc_attr( $key ), esc_attr( $value ) ); } } /** * `wp_insert_post_data`: keep the stored title, description and short * description when the form left them untouched and they changed after the * form was opened. * * @param mixed $data Slashed post data about to be written. * @param mixed $postarr Slashed request data. * @return mixed */ public function keepNewerText( $data, $postarr ) { if ( ! is_array( $data ) || ! is_array( $postarr ) || 'product' !== ( $data['post_type'] ?? '' ) ) { return $data; } $post_id = isset( $postarr['ID'] ) ? (int) $postarr['ID'] : 0; $prints = $this->postedFingerprints( $post_id ); if ( null === $prints ) { return $data; } $stored = self::storedText( $post_id ); if ( null === $stored ) { return $data; } foreach ( self::TEXT_FIELDS as $field ) { if ( ! isset( $data[ $field ], $prints[ $field ], $stored[ $field ] ) ) { continue; } $untouched = self::textFingerprint( (string) wp_unslash( $data[ $field ] ) ) === $prints[ $field ]; $changed_since = self::textFingerprint( $stored[ $field ] ) !== $prints[ $field ]; if ( $untouched && $changed_since ) { $data[ $field ] = wp_slash( $stored[ $field ] ); } } return $data; } /** * `woocommerce_admin_process_product_object`: keep the stored regular * price when the form left it untouched and it changed after the form was * opened. WooCommerce has set the form's values on the product and saves * it right after, so the older price is never written. * * @param mixed $product Product about to be saved from the form. * @return void */ public function keepNewerPrice( $product ): void { if ( ! $product instanceof \WC_Product ) { return; } $prints = $this->postedFingerprints( (int) $product->get_id() ); if ( null === $prints || ! isset( $prints[ self::PRICE_KEY ] ) ) { return; } $data = $product->get_data(); $stored = (string) ( $data['regular_price'] ?? '' ); $posted = (string) $product->get_regular_price( 'edit' ); if ( self::priceFingerprint( $posted ) === $prints[ self::PRICE_KEY ] && self::priceFingerprint( $stored ) !== $prints[ self::PRICE_KEY ] ) { $product->set_regular_price( $stored ); } } /** * `pre_post_update`: before a save of the product stores anything, read * every field that changed after the form was opened. A value equal to * the form's own is never taken for a newer one, so an update nested in * the save, after the form's older values were stored, keeps what an * earlier read found. * * @param mixed $postId Post id. * @return void */ public function readNewerValues( $postId ): void { $post_id = (int) $postId; $prints = $this->postedFingerprints( $post_id ); if ( null === $prints ) { return; } foreach ( $this->fields as $key => $field ) { if ( ! isset( $prints[ $key ] ) ) { continue; } $value = $field->read( $post_id ); if ( null !== $value && $field->fingerprint( $value ) !== $prints[ $key ] ) { $this->newer[ $post_id ][ $key ] = $value; } } } /** * `wp_after_insert_post`: put back each newer value the save replaced with * the form's older one. Runs on every update of the product in the * request, so a value stored again by a later save is put back again. * * @param mixed $postId Post id. * @return void */ public function putBackNewerValues( $postId ): void { $post_id = (int) $postId; if ( empty( $this->newer[ $post_id ] ) ) { return; } $prints = $this->postedFingerprints( $post_id ); if ( null === $prints ) { return; } foreach ( $this->newer[ $post_id ] as $key => $value ) { $field = $this->fields[ $key ]; try { $now = $field->read( $post_id ); if ( null !== $now && $field->fingerprint( $now ) === $prints[ $key ] ) { $field->restore( $post_id, $value ); } } catch ( \Throwable $e ) { Logger::error( 'admin', 'Product form guard could not keep a newer value', array( 'product_id' => $post_id, 'field' => $key, 'error' => $e->getMessage(), ) ); } } } /** * A text field's fingerprint: its visible text, with markup, entities and * runs of whitespace (including no-break spaces) reduced away. * * @param string $value Field value. * @return string */ public static function textFingerprint( string $value ): string { $text = html_entity_decode( wp_strip_all_tags( $value ), ENT_QUOTES | ENT_HTML5, 'UTF-8' ); $text = str_replace( "\xC2\xA0", ' ', $text ); $text = (string) preg_replace( '/\s+/u', ' ', $text ); return md5( trim( $text ) ); } /** * The fields kept after the save. * * @return GuardedField[] */ private static function defaultFields(): array { return array( new TermsField( 'tags', 'product_tag', true ), new TermsField( 'product_cat', 'product_cat', false ), new SeoMetaField( 'seo_title', 'title' ), new SeoMetaField( 'seo_description', 'description' ), new SeoMetaField( 'seo_focus_keyword', 'focus_keyword' ), ); } /** * The fingerprints this request's form carried for $postId, or null when * it carried none (any other save: REST, Quick Edit, autosave, a plugin's * own write) or they do not belong to this product. * * @param int $postId Post being saved. * @return array|null */ private function postedFingerprints( int $postId ): ?array { // phpcs:disable WordPress.Security.NonceVerification.Missing -- Verified right below, before any value is used. if ( $postId <= 0 || ! isset( $_POST[ self::FIELD ], $_POST['_wpnonce'] ) || ! is_array( $_POST[ self::FIELD ] ) ) { return null; } if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'update-post_' . $postId ) ) { return null; } $raw = wp_unslash( $_POST[ self::FIELD ] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Each value is reduced with sanitize_key() below. // phpcs:enable WordPress.Security.NonceVerification.Missing $prints = array(); foreach ( array_merge( array( 'post_id', self::PRICE_KEY ), self::TEXT_FIELDS, array_keys( $this->fields ) ) as $key ) { if ( isset( $raw[ $key ] ) && is_string( $raw[ $key ] ) ) { $prints[ $key ] = sanitize_key( $raw[ $key ] ); } } if ( (int) ( $prints['post_id'] ?? 0 ) !== $postId ) { return null; } return $prints; } /** * The product's stored text, read past every cache. * * @param int $postId Product id. * @return array|null */ private static function storedText( int $postId ): ?array { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Must see the committed row, not a cached copy. $row = $wpdb->get_row( $wpdb->prepare( "SELECT post_title, post_content, post_excerpt FROM {$wpdb->posts} WHERE ID = %d", $postId ), ARRAY_A ); return is_array( $row ) ? array_map( 'strval', $row ) : null; } /** * A price's fingerprint: WooCommerce's decimal form without trailing * zeros, so "10.50" and "10.5" match. * * @param string $value Price. * @return string */ private static function priceFingerprint( string $value ): string { return md5( (string) wc_format_decimal( trim( $value ), false, true ) ); } }