aioseo_writer = $aioseo_writer ?: new AioseoWriter(); } /** * Writes a single SEO meta field to a product. * * @param int $product_id The WooCommerce product ID. * @param string $meta_type The meta type: 'title', 'description', or 'focus_keyword'. * @param string $content The content to write (will be sanitized). * @param string $plugin_slug The SEO plugin slug (e.g., 'yoast', 'rankmath'). * * @return bool True on success, false on failure. * * @example * $writer = new SeoMetaWriter(); * $success = $writer->write(123, 'title', 'My Product Title', 'yoast'); */ public function write( $product_id, $meta_type, $content, $plugin_slug ) { $product_id = absint( $product_id ); if ( $product_id <= 0 ) { return false; } if ( 'aioseo' === $plugin_slug ) { return $this->writeAioseoData( $product_id, array( $meta_type => $content ) ); } $meta_keys = SeoPluginDetector::get_meta_keys( $plugin_slug ); if ( null === $meta_keys ) { return false; } $key_name = $meta_type . '_key'; if ( ! isset( $meta_keys[ $key_name ] ) ) { return false; } $meta_key = $meta_keys[ $key_name ]; if ( null === $meta_key ) { return false; } if ( ! is_scalar( $content ) ) { return false; } $sanitized_content = self::sanitize_value( (string) $content ); $current_value = \get_post_meta( $product_id, $meta_key, true ); $current_value = ( false === $current_value ) ? '' : $current_value; $normalized_current = self::sanitize_value( (string) $current_value ); $normalized_sanitized = $sanitized_content; if ( $normalized_current === $normalized_sanitized ) { return true; } $result = \update_post_meta( $product_id, $meta_key, \wp_slash( $sanitized_content ) ); if ( false !== $result ) { \AIPT\Api\ProductEditor\ProductEditorConcurrencyToken::bump_revision( $product_id ); } return false !== $result; } /** * Writes multiple SEO meta fields to a product in bulk. * * @param int $product_id The WooCommerce product ID. * @param array $data Array of meta fields to write, e.g., ['title' => '...', 'description' => '...']. * @param string $plugin_slug The SEO plugin slug (e.g., 'yoast', 'rankmath'). * @param string $gen Content-marking generation source. * @param int $job_id Applying automation job id, threaded into the * 'seo_meta' mark metadata so the premium * auto-on-publish breaker resets EXACTLY that job's * quota-failure streak on success. Omitted from the * mark meta when 0 (bulk generator / draft callers). * * @return array Array of results keyed by meta type, e.g., ['title' => true, 'description' => true]. * * @example * $writer = new SeoMetaWriter(); * $results = $writer->bulkWrite(123, [ * 'title' => 'My Product Title', * 'description' => 'My product description', * 'focus_keyword' => 'product keyword' * ], 'yoast'); * */ public function bulkWrite( $product_id, $data, $plugin_slug, string $gen = MetaKeys::GEN_BULK_ADVANCED, int $job_id = 0 ) { $results = array(); if ( ! is_array( $data ) ) { return $results; } $plugin_config = $this->pluginConfigFor( $plugin_slug ); $pending_changes = $this->pendingChangeKeys( absint( $product_id ), $data, $plugin_config ); $baseline_score = empty( $pending_changes ) ? null : SeoScoreResolver::capture_baseline_value( absint( $product_id ), $plugin_config ); if ( 'aioseo' === $plugin_slug ) { $results = $this->bulkWriteAioseo( absint( $product_id ), $data ); } else { foreach ( $data as $meta_type => $content ) { $results[ $meta_type ] = $this->write( $product_id, $meta_type, $content, $plugin_slug ); } } if ( ! empty( $results ) && count( array_filter( $results ) ) === count( $results ) ) { $mark_meta = array( 'gen' => $gen ); if ( $job_id > 0 ) { $mark_meta['job_id'] = $job_id; } ContentMarkService::mark( absint( $product_id ), 'seo_meta', $mark_meta ); } $changed_and_written = array_filter( $pending_changes, static function ( $writer_key ) use ( $results ) { return ! empty( $results[ $writer_key ] ); } ); if ( ! empty( $changed_and_written ) ) { SeoScoreResolver::write_baseline( absint( $product_id ), $plugin_slug, $baseline_score ); } return $results; } /** * Builds the minimal plugin config the score resolver needs. * * @param string $plugin_slug SEO plugin slug. * * @return array Config with `plugin_slug`, `plugin_name`, and `meta_keys`. */ private function pluginConfigFor( $plugin_slug ) { $meta_keys = SeoPluginDetector::get_meta_keys( (string) $plugin_slug ); return array( 'plugin_slug' => (string) $plugin_slug, 'plugin_name' => null, 'meta_keys' => is_array( $meta_keys ) ? $meta_keys : array(), ); } /** * Which fields in this payload would actually change the product's stored SEO meta. * * The caller needs the individual keys, not a single boolean, so a partially * successful bulk write can still record score staleness for exactly the fields * that both differed and landed. * * Reads current values through {@see SeoPluginDetector::get_seo_info()} with analysis * disabled, so AIOSEO's custom table and every other plugin's post meta are compared * through the same resolution path the read side uses. Comparison mirrors * {@see self::write()}'s own normalization so a value that write() would treat as a * no-op is not counted as a change here either. * * `keywords` (AIOSEO additional keyphrases) is intentionally not compared: it does not * participate in the score checks, and a focus-keyword change already covers the case * that matters. * * @param int $product_id WooCommerce product ID. * @param array $data Writer payload. * @param array $plugin_config Plugin config from {@see self::pluginConfigFor()}. * * @return string[] Writer keys whose incoming value differs from what is stored. */ private function pendingChangeKeys( $product_id, array $data, array $plugin_config ) { if ( $product_id <= 0 ) { return array(); } $current = SeoPluginDetector::get_seo_info( $product_id, $plugin_config, false ); $compared = array( 'title' => 'meta_title', 'description' => 'meta_description', 'focus_keyword' => 'focus_keyword', ); $changed = array(); foreach ( $compared as $writer_key => $info_key ) { if ( ! isset( $data[ $writer_key ] ) || ! is_scalar( $data[ $writer_key ] ) ) { continue; } $incoming = self::sanitize_value( (string) $data[ $writer_key ] ); $existing = self::sanitize_value( SeoFieldValueNormalizer::flatten( $current[ $info_key ] ?? '' ) ); if ( $incoming !== $existing ) { $changed[] = $writer_key; } } return $changed; } private function bulkWriteAioseo( int $product_id, array $data ): array { $results = array(); $payload = array(); foreach ( $data as $meta_type => $content ) { if ( ! $this->isAioseoFieldWritable( $meta_type, $content ) ) { $results[ $meta_type ] = false; continue; } $results[ $meta_type ] = null; $payload[ $meta_type ] = $content; } if ( empty( $payload ) ) { return $results; } $write_success = $this->writeAioseoData( $product_id, $payload ); foreach ( array_keys( $payload ) as $meta_type ) { $results[ $meta_type ] = $write_success; } return $results; } /** * Strips tags and control characters but keeps percent signs. * * WordPress's sanitize_text_field() removes every "%xx" hex pair, which * mangles SEO plugin variables such as %%category%%, %%date%% (Yoast) and * %category% (Rank Math). Every SEO write and unchanged-value comparison * goes through this one helper so they agree. * * @param string $value Raw value. * @param bool $multiline Keep line breaks (meta descriptions). * @return string Sanitized value. */ public static function sanitize_value( string $value, bool $multiline = false ): string { $value = \wp_check_invalid_utf8( $value ); $value = \wp_strip_all_tags( $value ); $value = (string) preg_replace( '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $value ); if ( $multiline ) { $value = (string) preg_replace( '/\r\n?/', "\n", $value ); $value = (string) preg_replace( '/[ \t]+/', ' ', $value ); return trim( (string) preg_replace( '/ ?\n ?/', "\n", $value ) ); } return trim( (string) preg_replace( '/\s+/', ' ', $value ) ); } private function writeAioseoData( int $product_id, array $data ): bool { try { $saved = $this->aioseo_writer->write( $product_id, $data ); if ( $saved ) { \AIPT\Api\ProductEditor\ProductEditorConcurrencyToken::bump_revision( $product_id ); } return $saved; } catch ( \Throwable $throwable ) { return false; } } private function isAioseoFieldWritable( $meta_type, $content ): bool { if ( 'keywords' === $meta_type ) { return is_array( $content ) || is_scalar( $content ); } return in_array( $meta_type, array( 'title', 'description', 'focus_keyword' ), true ) && is_scalar( $content ); } /** * Builds supported writer data from generated SEO meta fields. * * @param array $source Generated SEO meta data. * @param string $plugin_slug The SEO plugin slug. * @return array Writer-ready SEO meta data. */ public static function buildWriteData( array $source, string $plugin_slug ): array { $meta_keys = SeoPluginDetector::get_meta_keys( $plugin_slug ); if ( ! is_array( $meta_keys ) ) { return array(); } $write_data = array(); $field_map = array( 'meta_title' => array( 'writer_key' => 'title', 'meta_key' => 'title_key', 'allow_empty' => true ), 'meta_description' => array( 'writer_key' => 'description', 'meta_key' => 'description_key', 'allow_empty' => true ), 'focus_keyword' => array( 'writer_key' => 'focus_keyword', 'meta_key' => 'focus_keyword_key', 'allow_empty' => 'aioseo' === $plugin_slug ), ); foreach ( $field_map as $source_key => $field ) { if ( empty( $meta_keys[ $field['meta_key'] ] ) || ! isset( $source[ $source_key ] ) || ! is_string( $source[ $source_key ] ) ) { continue; } if ( ! $field['allow_empty'] && '' === trim( $source[ $source_key ] ) ) { continue; } $write_data[ $field['writer_key'] ] = $source[ $source_key ]; } return $write_data; } }