'object', 'additionalProperties' => false, 'required' => array( 'id', 'find', 'replace' ), 'properties' => array( 'id' => array( 'type' => 'integer', 'description' => __( 'The post id to edit.', 'gripmcp' ), 'minimum' => 1, ), 'find' => array( 'type' => 'string', 'description' => __( 'Exact existing text to replace. Include enough surrounding context to be unique.', 'gripmcp' ), 'minLength' => 1, ), 'replace' => array( 'type' => 'string', 'description' => __( 'Replacement text. Use an empty string to delete the matched passage.', 'gripmcp' ), ), 'field' => array( 'type' => 'string', 'description' => __( 'Which field to edit. Defaults to "content".', 'gripmcp' ), 'enum' => array( 'content', 'excerpt' ), 'default' => 'content', ), 'all' => array( 'type' => 'boolean', 'description' => __( 'Replace every occurrence instead of requiring exactly one match.', 'gripmcp' ), 'default' => false, ), ), ); } protected function required_capability(): string { return 'edit_posts'; } protected function run( array $arguments, Request_Context $context ): Tool_Result { $id = (int) $arguments['id']; $post = get_post( $id ); if ( ! $post instanceof \WP_Post ) { return $this->fail( sprintf( /* translators: %d: post id. */ __( 'No post found with id %d.', 'gripmcp' ), $id ) ); } // Additional CSS answers to edit_css: its post type maps edit_post to // a capability no role holds. $is_css = Custom_Css::is_css( $post ); if ( $is_css && ! Custom_Css::writable() ) { return $this->fail( Custom_Css::read_only() ); } if ( $is_css && ! Custom_Css::can_edit( $context ) ) { return $this->fail( Custom_Css::forbidden() ); } if ( ! $is_css && ! $context->user_can( 'edit_post', $id ) ) { return $this->fail( __( 'You do not have permission to edit this post.', 'gripmcp' ) ); } // Orders and fonts are not changed as plain posts at all: refused // before any field is looked at. $locked = Post_Access::change_error( $post, Post_Access::CHANGE_UPDATE ); if ( '' !== $locked ) { return $this->fail( $locked ); } $field = 'excerpt' === ( $arguments['field'] ?? 'content' ) ? 'excerpt' : 'content'; $column = 'excerpt' === $field ? 'post_excerpt' : 'post_content'; // The edit would succeed and change nothing visitors see. if ( 'content' === $field && Elementor_Support::builds( $id ) ) { return $this->fail( Elementor_Support::body_note( $id ) ); } $haystack = (string) $post->{$column}; $find = (string) $arguments['find']; $replace = (string) $arguments['replace']; $all = ! empty( $arguments['all'] ); if ( '' === $haystack ) { return $this->fail( sprintf( /* translators: %s: field name. */ __( 'The %s field is empty, so there is nothing to edit.', 'gripmcp' ), $field ) ); } $matches = $this->locate( $haystack, $find ); if ( empty( $matches ) ) { return $this->fail( $this->no_match_message( $haystack, $find, $field ) ); } if ( count( $matches ) > 1 && ! $all ) { return $this->fail( $this->ambiguous_message( $haystack, $matches ) ); } $updated = $this->apply( $haystack, $matches, $find, $replace ); $markup = $is_css && 'content' === $field ? Custom_Css::markup_error( $updated ) : null; if ( null !== $markup ) { return $this->fail( $markup ); } // Code already in the field stays; code the edit adds is left to the // person, unless the plan adds code with approval. $code = $is_css ? '' : Added_Code::refusal( Added_Code::added( $haystack, $updated ) ); if ( '' !== $code ) { return $this->fail( $code ); } // The site's saved styles must stay a document WordPress reads. $change = Post_Access::change_error( $post, Post_Access::CHANGE_UPDATE, array( $column => $updated ) ); if ( '' !== $change ) { return $this->fail( $change ); } $result = wp_update_post( wp_slash( array( 'ID' => $id, $column => $updated, ) ), true ); if ( is_wp_error( $result ) ) { return $this->fail( sprintf( /* translators: %s: error message. */ __( 'Failed to save the edit: %s', 'gripmcp' ), $result->get_error_message() ) ); } $fresh = get_post( $id ); $stored = $fresh instanceof \WP_Post ? (string) $fresh->{$column} : ''; $payload = array( 'id' => $id, 'field' => $field, 'replacements_made' => count( $matches ), ); $summary = sprintf( /* translators: 1: number of replacements, 2: field, 3: post id. */ _n( 'Made %1$d replacement in the %2$s of post #%3$d.', 'Made %1$d replacements in the %2$s of post #%3$d.', count( $matches ), 'gripmcp' ), count( $matches ), $field, $id ); // WordPress filters (e.g. kses for users without unfiltered_html) can // silently alter what was saved. Report it so the next edit is not // built against a version that no longer exists on the site. if ( $stored !== $updated ) { $payload['altered_on_save'] = true; $payload['stored_excerpt'] = $this->snippet( $stored, 0, 200 ); $summary .= ' ' . __( 'Note: WordPress changed the content as it saved (content filtering or block cleanup). The stored value differs from what was sent; re-read the post before editing again.', 'gripmcp' ); } if ( $is_css && $fresh instanceof \WP_Post ) { $after = Custom_Css::after_save( $fresh ); $payload['refreshed'] = $after['refreshed']; if ( '' !== $after['summary'] ) { $summary .= ' ' . $after['summary']; } if ( ! empty( $after['notes'] ) ) { $payload['notes'] = $after['notes']; $summary .= ' ' . implode( ' ', $after['notes'] ); } } return $this->data( $payload, $summary ); } /** * The field with the matched passages replaced, right to left so earlier * offsets stay valid. * * @param string $haystack Field as stored. * @param array> $matches What locate() found. * @param string $find Search text. * @param string $replace Replacement. */ private function apply( string $haystack, array $matches, string $find, string $replace ): string { $updated = $haystack; foreach ( array_reverse( $matches ) as $match ) { $updated = substr( $updated, 0, $match['offset'] ) . $this->replacement_for( substr( $haystack, $match['offset'], $match['length'] ), $find, $replace ) . substr( $updated, $match['offset'] + $match['length'] ); } return $updated; } /** * The code this edit would add to the post as it is now * (Support\Added_Code), worked out as run() makes the edit. Empty when * the edit would not run (no match, or several without "all"); a theme's * Additional CSS has its own rules. * * @param array $arguments Validated arguments. * @return array */ public function added_code( array $arguments ): array { $post = get_post( (int) ( $arguments['id'] ?? 0 ) ); if ( ! $post instanceof \WP_Post || Custom_Css::is_css( $post ) ) { return array(); } $column = 'excerpt' === ( $arguments['field'] ?? 'content' ) ? 'post_excerpt' : 'post_content'; $haystack = (string) $post->{$column}; $find = (string) ( $arguments['find'] ?? '' ); if ( '' === $haystack || '' === $find ) { return array(); } $matches = $this->locate( $haystack, $find ); if ( empty( $matches ) || ( count( $matches ) > 1 && empty( $arguments['all'] ) ) ) { return array(); } return Added_Code::added( $haystack, $this->apply( $haystack, $matches, $find, (string) ( $arguments['replace'] ?? '' ) ) ); } /** * An edit that adds code, on a plan that allows it, is held for approval * like a delete, so the person sees the code first. * * @param array $arguments Validated arguments. */ public function is_destructive_call( array $arguments ): bool { return Added_Code::allowed() && ! empty( $this->added_code( $arguments ) ); } /** * What "Destructive actions: Off" says about it. * * @param array $arguments Validated arguments. */ public function destructive_refusal( array $arguments ): string { return Added_Code::off_message( $this->added_code( $arguments ) ); } /** * The post as it is when an edit that adds code is held: the edit is made * on the text as it is when approved, so a change in between stops it. * * @param array $arguments Validated arguments. */ public function approval_state( array $arguments ): string { return empty( $this->added_code( $arguments ) ) ? '' : Added_Code::post_state( (int) ( $arguments['id'] ?? 0 ) ); } /** * Find every occurrence of $find in $haystack, tolerant of quote and entity * variants. Returns a list of ['offset' => int, 'length' => int] against the * original haystack, or an empty array if none. * * @param string $haystack Text to search. * @param string $find Text to find. * @return array> */ private function locate( string $haystack, string $find ): array { // Fast path: an exact literal match needs no fuzzing. $offset = 0; $exact = array(); $literal = strlen( $find ); while ( $literal > 0 ) { $pos = strpos( $haystack, $find, $offset ); if ( false === $pos ) { break; } $exact[] = array( 'offset' => $pos, 'length' => $literal, ); $offset = $pos + $literal; } if ( ! empty( $exact ) ) { return $exact; } // Fuzzy path: build a byte-oriented pattern from the canonical form of // $find where each quote/space/ampersand also matches its variants. $pattern = $this->build_flexible_pattern( $find ); if ( '' === $pattern ) { return array(); } $found = preg_match_all( '/' . $pattern . '/', $haystack, $m, PREG_OFFSET_CAPTURE ); if ( ! $found ) { return array(); } $matches = array(); foreach ( $m[0] as $capture ) { $matches[] = array( 'offset' => (int) $capture[1], 'length' => strlen( (string) $capture[0] ), ); } return $matches; } /** * The replacement for one matched passage. When "&" in the search text * matched "&" in the stored text, a bare "&" in the replacement is * written as "&" too, so the edit changes only what was asked and * the stored markup keeps its own form. Entities already in the * replacement (" ", "’") are left as they are. * * @param string $matched Stored text that matched. * @param string $find Search text. * @param string $replace Replacement as sent. */ private function replacement_for( string $matched, string $find, string $replace ): string { if ( false === strpos( $matched, '&' ) || false !== strpos( $find, '&' ) ) { return $replace; } return (string) preg_replace( '/&(?![a-zA-Z][a-zA-Z0-9]*;|#[0-9]+;|#[xX][0-9a-fA-F]+;)/', '&', $replace ); } /** * Map curly quotes, non-breaking spaces, and a handful of entities back to * their plain form so a search works regardless of which side used which. * * @param string $text Text. */ private function canonicalize( string $text ): string { $text = str_replace( array( "\xe2\x80\x98", "\xe2\x80\x99", '’', '‘', '’', '‘', ''', ''' ), "'", $text ); $text = str_replace( array( "\xe2\x80\x9c", "\xe2\x80\x9d", '“', '”', '“', '”', '"' ), '"', $text ); $text = str_replace( array( "\xc2\xa0", ' ' ), ' ', $text ); $text = str_replace( '&', '&', $text ); return $text; } /** * Build a regex (no delimiters) from $find whose literal characters are * exact but whose quotes/spaces/ampersands also match their variants. * * @param string $find Text to find. */ private function build_flexible_pattern( string $find ): string { $canonical = $this->canonicalize( $find ); $quoted = preg_quote( $canonical, '/' ); $single = '(?:\'|\xe2\x80\x98|\xe2\x80\x99|’|‘|'|’|‘|')'; $double = '(?:"|\xe2\x80\x9c|\xe2\x80\x9d|“|”|“|”|")'; $space = '(?:[ ]|\xc2\xa0| )'; $amp = '(?:&|&)'; // Ampersand first, with a sentinel byte that cannot appear in text. $quoted = str_replace( '\&', "\x01", $quoted ); // preg_quote leaves & as &, but be safe. $quoted = str_replace( '&', "\x01", $quoted ); $quoted = str_replace( "\x01", $amp, $quoted ); $quoted = str_replace( "'", $single, $quoted ); $quoted = str_replace( '"', $double, $quoted ); $quoted = str_replace( ' ', $space, $quoted ); return $quoted; } /** * Build a helpful "no match" error, pointing at the nearest text actually * stored so the retry is informed rather than a guess. * * @param string $haystack Field content. * @param string $find Text that was not found. * @param string $field Field name. */ private function no_match_message( string $haystack, string $find, string $field ): string { $near = $this->nearest_passage( $haystack, $find ); $message = sprintf( /* translators: %s: field name. */ __( 'That exact text was not found in the %s. It may differ by punctuation, spacing, or HTML markup from what is stored.', 'gripmcp' ), $field ); if ( null !== $near ) { $message .= ' ' . sprintf( /* translators: %s: nearby stored text. */ __( 'The closest stored passage is: "%s". Read the post and copy the exact stored text.', 'gripmcp' ), $near ); } return $message; } /** * Describe the ambiguous case: several matches, but "all" was not set. * * @param string $haystack Field content. * @param array> $matches Located matches. */ private function ambiguous_message( string $haystack, array $matches ): string { $contexts = array(); foreach ( array_slice( $matches, 0, 3 ) as $match ) { $contexts[] = '…' . $this->snippet( $haystack, max( 0, $match['offset'] - 25 ), 70 ) . '…'; } return sprintf( /* translators: 1: match count, 2: sample contexts. */ __( 'That text appears %1$d times, so it is ambiguous. Add surrounding context to make it unique, or set "all" to true to replace every occurrence. Occurrences near: %2$s', 'gripmcp' ), count( $matches ), implode( ' | ', $contexts ) ); } /** * Find the longest leading run of words from $find that occurs in $haystack, * and return a short context snippet around it. Null if nothing overlaps. * * @param string $haystack Field content. * @param string $find Text that was not found. */ private function nearest_passage( string $haystack, string $find ): ?string { $canon_hay = strtolower( $this->canonicalize( $haystack ) ); $canon_find = $this->canonicalize( $find ); $words = preg_split( '/\s+/', trim( $canon_find ) ) ?: array(); for ( $take = count( $words ); $take >= 2; $take-- ) { $probe = strtolower( implode( ' ', array_slice( $words, 0, $take ) ) ); if ( '' === $probe ) { continue; } $pos = strpos( $canon_hay, $probe ); if ( false !== $pos ) { return $this->snippet( $haystack, max( 0, $pos - 10 ), strlen( $probe ) + 60 ); } } return null; } /** * Extract a clean, length-limited snippet from a string. * * @param string $text Source. * @param int $start Byte offset. * @param int $length Bytes to take. */ private function snippet( string $text, int $start, int $length ): string { $size = strlen( $text ); $start = max( 0, min( $start, $size ) ); $end = min( $size, $start + max( 0, $length ) ); // A byte offset can land inside a multibyte character (Hindi, emoji); // cut half of one shows as "?". Both ends move back to where a // character starts. while ( $start > 0 && $start < $size && 0x80 === ( ord( $text[ $start ] ) & 0xC0 ) ) { --$start; } while ( $end > $start && $end < $size && 0x80 === ( ord( $text[ $end ] ) & 0xC0 ) ) { --$end; } $slice = substr( $text, $start, $end - $start ); $slice = preg_replace( '/\s+/', ' ', $slice ); return trim( (string) $slice ); } }