$chars * 0.6 ) { $cut = mb_substr( $cut, 0, $space ); } return rtrim( $cut, " \t,.;:-–—" ) . '…'; } /** * Plain text from post HTML: no block comments, shortcodes, tags or extra spaces. * * @param string $html HTML. * @return string */ function aatg_plain_text( $html ) { $html = preg_replace( '//s', ' ', aatg_valid_utf8( $html ) ); $text = wp_strip_all_tags( strip_shortcodes( (string) $html ) ); $text = html_entity_decode( $text, ENT_QUOTES | ENT_HTML5, 'UTF-8' ); return aatg_squish( $text ); } /** * Post types and statuses searched for image usage. * * @return array array( 'types' => string[], 'statuses' => string[] ). */ function aatg_usage_scope() { $types = array_values( array_diff( get_post_types( array( 'public' => true ) ), array( 'attachment' ) ) ); return array( 'types' => $types, 'statuses' => array( 'publish', 'draft', 'pending', 'private', 'future' ), ); } /** * Find the best single place an image is used. * * Order: a post whose content embeds it, then a post using it as the featured * image, then the attachment's parent post. A brand-new upload can't be in any * content yet, so the 'upload' phase only checks the parent. * * @param int $post_ID Attachment ID. * @param string $phase 'upload', 'manual' or 'bulk'. * @return array|null array( 'post_id' => int, 'type' => 'embedded'|'featured'|'parent' ), or null. */ function aatg_find_image_usage( $post_ID, $phase = 'manual' ) { global $wpdb; $post_ID = (int) $post_ID; $scope = aatg_usage_scope(); if ( ! $post_ID || ! $scope['types'] ) { return null; } if ( 'upload' === $phase ) { return aatg_parent_usage( $post_ID, $scope ); } $type_in = implode( ',', array_fill( 0, count( $scope['types'] ), '%s' ) ); $status_in = implode( ',', array_fill( 0, count( $scope['statuses'] ), '%s' ) ); $args = array_merge( $scope['types'], $scope['statuses'], array( '%' . $wpdb->esc_like( 'wp-image-' . $post_ID ) . '%', '%' . $wpdb->esc_like( '"id":' . $post_ID ) . '%', ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- placeholders are built above. $candidates = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_content FROM {$wpdb->posts} WHERE post_type IN ($type_in) AND post_status IN ($status_in) AND ( post_content LIKE %s OR post_content LIKE %s ) ORDER BY ( post_status = 'publish' ) DESC, post_date DESC LIMIT 3", $args ) ); $pattern = '/wp-image-' . $post_ID . '(?!\d)|"id":' . $post_ID . '(?!\d)/'; foreach ( (array) $candidates as $candidate ) { if ( preg_match( $pattern, $candidate->post_content ) ) { return array( 'post_id' => (int) $candidate->ID, 'type' => 'embedded', ); } } $featured = get_posts( array( 'post_type' => $scope['types'], 'post_status' => $scope['statuses'], 'meta_key' => '_thumbnail_id', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key 'meta_value' => $post_ID, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value 'posts_per_page' => 1, 'fields' => 'ids', 'no_found_rows' => true, 'suppress_filters' => true, ) ); if ( $featured ) { return array( 'post_id' => (int) $featured[0], 'type' => 'featured', ); } return aatg_parent_usage( $post_ID, $scope ); } /** * The attachment's parent post, when it is a public post in a counted status. * * @param int $post_ID Attachment ID. * @param array $scope From aatg_usage_scope(). * @return array|null */ function aatg_parent_usage( $post_ID, array $scope ) { $parent = (int) wp_get_post_parent_id( $post_ID ); if ( $parent && in_array( get_post_type( $parent ), $scope['types'], true ) && in_array( get_post_status( $parent ), $scope['statuses'], true ) ) { return array( 'post_id' => $parent, 'type' => 'parent', ); } return null; } /** * Turn raw post content into HTML whose structure matches what visitors see, * without running other plugins' content filters: * - classic [caption] shortcodes become
; * - classic (non-block) content gets paragraphs via wpautop(); * - remaining shortcode tags are removed but their inner content is kept. * * @param string $content Raw post_content. * @return string */ function aatg_prepare_content_html( $content ) { $content = (string) $content; $is_blocks = function_exists( 'has_blocks' ) && has_blocks( $content ); $content = preg_replace( '//s', '', $content ); $content = preg_replace_callback( '/\[caption[^\]]*\](.*?)\[\/caption\]/is', function ( $m ) { if ( preg_match( '/^(.*?]*>(?:\s*<\/a>)?)(.*)$/is', $m[1], $parts ) ) { return '
' . $parts[1] . '
' . trim( $parts[2] ) . '
'; } return '
' . $m[1] . '
'; }, $content ); if ( ! $is_blocks ) { $content = wpautop( $content ); } return preg_replace( '/\[\/?[a-z][\w-]*(?:\s[^\]]*)?\]/i', '', $content ); } /** * Text around an embedded image: nearest preceding heading, the paragraphs * before and after its block, and its caption. * * @param string $html Raw post content. * @param int $attachment_id Attachment ID. * @return array array( 'heading' => string, 'before' => string, 'after' => string, 'caption' => string ). */ function aatg_extract_embed_context( $html, $attachment_id ) { $out = array( 'heading' => '', 'before' => '', 'after' => '', 'caption' => '', ); $html = aatg_prepare_content_html( $html ); if ( '' === trim( $html ) || ! class_exists( 'DOMDocument' ) ) { return $out; } $doc = new DOMDocument(); $previous = libxml_use_internal_errors( true ); $doc->loadHTML( '
' . $html . '
', LIBXML_NONET ); libxml_clear_errors(); libxml_use_internal_errors( $previous ); $xpath = new DOMXPath( $doc ); $root = $xpath->query( '//div[@id="aatg-root"]' )->item( 0 ); $img = $xpath->query( '//img[contains(concat(" ", normalize-space(@class), " "), " wp-image-' . (int) $attachment_id . ' ")]' )->item( 0 ); if ( ! $root || ! $img ) { return $out; } $caption = $xpath->query( 'ancestor::figure[1]/figcaption', $img )->item( 0 ); if ( $caption ) { $out['caption'] = aatg_truncate( $caption->textContent, AATG_CONTEXT_FIELD_LIMIT ); } // The image's top-level block. $block = $img; while ( $block->parentNode && ! $block->parentNode->isSameNode( $root ) ) { $block = $block->parentNode; } for ( $node = $block->previousSibling; $node; $node = $node->previousSibling ) { if ( XML_ELEMENT_NODE !== $node->nodeType ) { continue; } $text = aatg_squish( $node->textContent ); if ( '' === $text ) { continue; } if ( preg_match( '/^h[1-6]$/i', $node->nodeName ) ) { $out['heading'] = aatg_truncate( $text, AATG_CONTEXT_FIELD_LIMIT ); break; } if ( '' === $out['before'] && 'p' === strtolower( $node->nodeName ) ) { $out['before'] = aatg_truncate( $text, AATG_CONTEXT_FIELD_LIMIT ); } } for ( $node = $block->nextSibling; $node; $node = $node->nextSibling ) { if ( XML_ELEMENT_NODE === $node->nodeType && 'p' === strtolower( $node->nodeName ) ) { $text = aatg_squish( $node->textContent ); if ( '' !== $text ) { $out['after'] = aatg_truncate( $text, AATG_CONTEXT_FIELD_LIMIT ); break; } } if ( XML_ELEMENT_NODE === $node->nodeType && preg_match( '/^h[1-6]$/i', $node->nodeName ) ) { break; // Next section. } } return $out; } /** * Context lines for a usage found by aatg_find_image_usage(). * * @param array $usage Usage. * @param int $attachment_id Attachment ID. * @return string[] */ function aatg_usage_context_lines( array $usage, $attachment_id ) { $post = get_post( $usage['post_id'] ); if ( ! $post ) { return array(); } $type_object = get_post_type_object( $post->post_type ); $type_label = $type_object ? $type_object->labels->singular_name : $post->post_type; $type_label = function_exists( 'mb_strtolower' ) ? mb_strtolower( $type_label ) : strtolower( $type_label ); $title = aatg_truncate( aatg_plain_text( $post->post_title ), 120 ); $lines = array(); $lines[] = '' !== $title ? sprintf( 'Used in the %s "%s".', $type_label, $title ) : sprintf( 'Used in a %s.', $type_label ); if ( 'embedded' === $usage['type'] ) { $parts = aatg_extract_embed_context( $post->post_content, $attachment_id ); $labels = array( 'heading' => 'Nearest heading', 'before' => 'Text before the image', 'after' => 'Text after the image', 'caption' => 'Image caption', ); foreach ( $labels as $key => $label ) { if ( '' !== $parts[ $key ] ) { $lines[] = $label . ': ' . $parts[ $key ]; } } } else { $summary = has_excerpt( $post ) ? $post->post_excerpt : $post->post_content; $summary = aatg_truncate( aatg_plain_text( $summary ), AATG_CONTEXT_FIELD_LIMIT ); if ( '' !== $summary ) { $lines[] = 'Summary: ' . $summary; } } return $lines; } /** * WooCommerce product details when the image is a product's main image, in * its gallery, or attached to a product. On upload only the parent can match. * * @param int $post_ID Attachment ID. * @param string $phase 'upload', 'manual' or 'bulk'. * @return string[] Zero or one line. */ function aatg_get_woocommerce_context( $post_ID, $phase = 'manual' ) { global $wpdb; if ( ! function_exists( 'wc_get_product' ) ) { return array(); } $post_ID = (int) $post_ID; $statuses = aatg_usage_scope()['statuses']; $product_id = 0; $main = 'upload' === $phase ? array() : get_posts( array( 'post_type' => 'product', 'post_status' => $statuses, 'meta_key' => '_thumbnail_id', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key 'meta_value' => $post_ID, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value 'posts_per_page' => 1, 'fields' => 'ids', 'no_found_rows' => true, 'suppress_filters' => true, ) ); if ( $main ) { $product_id = (int) $main[0]; } if ( ! $product_id && 'upload' !== $phase ) { $rows = $wpdb->get_results( $wpdb->prepare( "SELECT post_id, meta_value FROM {$wpdb->postmeta} WHERE meta_key = '_product_image_gallery' AND meta_value LIKE %s LIMIT 10", '%' . $wpdb->esc_like( (string) $post_ID ) . '%' ) ); foreach ( (array) $rows as $row ) { if ( in_array( (string) $post_ID, array_map( 'trim', explode( ',', $row->meta_value ) ), true ) && in_array( get_post_status( $row->post_id ), $statuses, true ) ) { $product_id = (int) $row->post_id; break; } } } if ( ! $product_id ) { $parent = (int) wp_get_post_parent_id( $post_ID ); if ( $parent && 'product' === get_post_type( $parent ) ) { $product_id = $parent; } } $product = $product_id ? wc_get_product( $product_id ) : null; if ( ! $product ) { return array(); } $line = 'Product: ' . aatg_truncate( aatg_plain_text( $product->get_name() ), 120 ) . '.'; $categories = wp_get_post_terms( $product_id, 'product_cat', array( 'fields' => 'names' ) ); if ( ! is_wp_error( $categories ) && $categories ) { $line .= ' Categories: ' . implode( ', ', array_slice( array_map( 'aatg_plain_text', $categories ), 0, 3 ) ) . '.'; } $description = aatg_truncate( aatg_plain_text( $product->get_short_description() ), AATG_CONTEXT_FIELD_LIMIT ); if ( '' !== $description ) { $line .= ' Description: ' . $description; } return array( $line ); } /** * Keep lines within a total character budget, trimming the last one that fits. * * @param string[] $lines Lines in priority order. * @param int $budget Total characters. * @return string[] */ function aatg_apply_context_budget( array $lines, $budget ) { $kept = array(); $used = 0; foreach ( $lines as $line ) { $length = mb_strlen( $line ); if ( $used + $length <= $budget ) { $kept[] = $line; $used += $length; continue; } $room = $budget - $used; if ( $room > 40 ) { $kept[] = aatg_truncate( $line, $room - 1 ); } break; } return $kept; } /** * Whether a file name was made by a camera, phone or app rather than a person * (IMG_4821, PXL_20240115_120000, Screenshot 2026-10-21 at 10.15, a UUID …), * and so says nothing about the picture. * * @param string $name File name without extension. * @return bool */ function aatg_is_generic_file_name( $name ) { $name = trim( (string) $name ); return '' === $name || (bool) preg_match( '/^(img|dsc[fn]?|dcim|pxl|mvimg|image|photo|pic|picture|screenshot|screen[\s_-]?shot|untitled|capture|scan|wp|whatsapp[\s_-]image|signal|file|download)[\s_\-.:()\d]*(at[\s_\-.:()\d]*)?$/i', $name ) || (bool) preg_match( '/^[\d\s_\-.:()]+$/', $name ) || (bool) preg_match( '/^[a-f\d]{8,}(-[a-f\d]{4,}){0,4}$/i', $name ); } /** * "Image file name: xyz.jpg. " when the option is on (default for new installs) * and the name was chosen by a person; otherwise ''. Kept from 1.x. * * @param int $post_ID Attachment ID. * @return string */ function aatg_file_name_context( $post_ID ) { if ( get_option( 'aatg_send_filename', 'on' ) !== 'on' ) { return ''; } $path = get_attached_file( $post_ID ); if ( ! $path ) { return ''; } // WordPress adds "-scaled" to big uploads; send the name the person chose. $filename = preg_replace( '/-scaled(\.[a-z0-9]+)$/i', '$1', wp_basename( $path ) ); if ( aatg_is_generic_file_name( pathinfo( $filename, PATHINFO_FILENAME ) ) ) { return ''; } return 'Image file name: ' . $filename . '. '; } /** * All context lines for an image, in the order they are given to the model. * * @param int $post_ID Attachment ID. * @param string $phase 'upload', 'manual' or 'bulk'. * @return string[] */ function aatg_get_image_context_lines( $post_ID, $phase = 'manual' ) { $lines = array(); if ( 'on' === get_option( 'aatg_use_page_context', 'on' ) ) { $product = aatg_get_woocommerce_context( $post_ID, $phase ); $usage = aatg_find_image_usage( $post_ID, $phase ); // A product's own page adds nothing the product line doesn't already say. if ( $usage && ! ( $product && 'product' === get_post_type( $usage['post_id'] ) ) ) { $lines = aatg_usage_context_lines( $usage, $post_ID ); } $lines = aatg_apply_context_budget( array_merge( $lines, $product ), AATG_CONTEXT_BUDGET ); } $site_name = aatg_plain_text( get_bloginfo( 'name' ) ); if ( '' !== $site_name ) { $lines[] = 'Site: ' . $site_name . '.'; } $site_context = aatg_squish( get_option( 'aatg_site_context', '' ) ); if ( '' !== $site_context ) { $lines[] = 'Site context: ' . $site_context; } $file_name = trim( aatg_file_name_context( $post_ID ) ); if ( '' !== $file_name ) { $lines[] = $file_name; } /** * Filter the context lines given to the model for an image. * * @param string[] $lines Context lines. * @param int $post_ID Attachment ID. * @param string $phase 'upload', 'manual' or 'bulk'. */ return array_values( (array) apply_filters( 'aatg_image_context', $lines, $post_ID, $phase ) ); }