array( label, type, kind ). Kinds: * root inner HTML of the block's root element (

…

) * el:TAG inner HTML of the first TAG element (…,
…
) * attr:TAG:ATTR an attribute of the first TAG element * whole the block's entire inner HTML * image the image itself (attachment id → id attr, src, wp-image-N class) */ const SPECS = array( 'core/paragraph' => array( 'text' => array( 'Text', 'html', 'root' ) ), 'core/heading' => array( 'text' => array( 'Text', 'html', 'root' ) ), 'core/list-item' => array( 'text' => array( 'Text', 'html', 'root' ) ), // a list item holding a nested list: see LEAD 'core/preformatted' => array( 'text' => array( 'Text', 'html', 'root' ) ), 'core/verse' => array( 'text' => array( 'Text', 'html', 'root' ) ), 'core/code' => array( 'code' => array( 'Code', 'html', 'el:code' ) ), 'core/pullquote' => array( 'text' => array( 'Quote', 'html', 'el:p' ), 'citation' => array( 'Citation', 'html', 'el:cite' ), ), 'core/button' => array( 'text' => array( 'Text', 'html', 'el:a' ), 'url' => array( 'Link', 'url', 'attr:a:href' ), ), 'core/image' => array( 'image' => array( 'Image', 'image', 'image' ), 'alt' => array( 'Alt text', 'text', 'attr:img:alt' ), 'caption' => array( 'Caption', 'html', 'el:figcaption' ), ), 'core/html' => array( 'html' => array( 'Custom HTML', 'html', 'whole' ) ), 'core/shortcode' => array( 'text' => array( 'Shortcode', 'textarea', 'whole' ) ), ); /** * Blocks whose own text sits before their child blocks (a list item with a nested list): * the text after this opening tag, up to the first child block. */ const LEAD = array( 'core/list-item' => 'li' ); /** * The only tags a block's text part may contain: the inline formatting the block editor's * text fields keep. Anything else (a

,

, …) would break the block's HTML. */ const INLINE_TAGS = array( 'a', 'abbr', 'b', 'bdi', 'bdo', 'br', 'cite', 'code', 'del', 'dfn', 'em', 'i', 'img', 'ins', 'kbd', 'mark', 'q', 's', 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'time', 'u', 'var', 'wbr' ); /** What the last write intended, per post, for verify_column(): content, target path, target key. */ private static $intended = array(); /** String attributes of dynamic (HTML-less) blocks that hold visible text. */ const TEXT_ATTRS = array( 'content', 'text', 'title', 'heading', 'subheading', 'description', 'label', 'buttonText', 'caption' ); public function id() { return 'gutenberg'; } public function name() { return 'Block editor'; } public function available() { return function_exists( 'parse_blocks' ); } public function detect( \WP_Post $post ) { return post_type_supports( $post->post_type, 'editor' ) && has_blocks( $post->post_content ) && 'builder' !== get_post_meta( $post->ID, '_elementor_edit_mode', true ); } public function post_column( $locator ) { return 'post_content'; } private static function map( \WP_Post $post ) { $nodes = Block_Map::build( $post->post_content ); if ( null === $nodes ) { throw new Tool_Error( esc_html( "The blocks on #{$post->ID} don't nest correctly (a block comment is unmatched), so ADI won't edit them. Open it in the block editor and let it repair the content first." ) ); } return $nodes; } public function list_fields( \WP_Post $post ) { $fields = array(); try { $nodes = self::map( $post ); } catch ( Tool_Error $e ) { // Don't hide the rest of the page (title, excerpt…) because one block comment is unmatched. return array( array( 'locator' => 'blocks', 'label' => 'Blocks', 'type' => 'readonly', 'value' => null, 'writable' => false, 'note' => Tool_Error::text( $e ), ), ); } foreach ( Block_Map::flatten( $nodes ) as $node ) { foreach ( $this->node_fields( $post->post_content, $node ) as $field ) { $fields[] = $field; } } return $fields; } public function read( \WP_Post $post, $locator ) { if ( 'blocks' === $locator ) { foreach ( $this->list_fields( $post ) as $field ) { if ( 'blocks' === $field['locator'] ) { return $field; } } return null; } if ( ! preg_match( '#^(\d+(?:\.\d+)*)/([A-Za-z_]+)\z#', $locator, $m ) ) { return null; } $node = Block_Map::find( self::map( $post ), $m[1] ); if ( ! $node ) { return null; } foreach ( $this->node_fields( $post->post_content, $node ) as $field ) { if ( $field['locator'] === $locator ) { return $field; } } return null; } private static function label_of( $name ) { $type = \WP_Block_Type_Registry::get_instance()->get_registered( $name ); return $type && ! empty( $type->title ) ? $type->title : ucwords( str_replace( array( 'core/', '-', '/' ), array( '', ' ', ' › ' ), $name ) ); } private function node_fields( $content, array $node ) { $crumbs = array_map( array( self::class, 'label_of' ), $node['trail'] ); $where = ( $crumbs ? implode( ' › ', $crumbs ) . ' › ' : '' ) . self::label_of( $node['name'] ); $base = array( 'block' => $node['name'], 'within' => $node['trail'] ); $leaf = ! $node['children'] && ! $node['void']; $inner = $node['void'] ? '' : Block_Map::inner( $content, $node ); if ( 'core/block' === $node['name'] ) { $ref = isset( $node['attrs']['ref'] ) ? (int) $node['attrs']['ref'] : 0; return array( $base + array( 'locator' => $node['path'] . '/pattern', 'label' => "$where (synced pattern)", 'type' => 'readonly', 'value' => $ref, 'writable' => false, 'note' => "A synced pattern (#$ref): its content is shared by every page that uses it, so ADI doesn't edit it from here.", ), ); } $out = array(); if ( isset( self::LEAD[ $node['name'] ] ) && $node['children'] ) { $lead = self::lead( $content, $node ); if ( null !== $lead ) { $out[] = $base + array( 'locator' => $node['path'] . '/text', 'label' => "$where: Text", 'type' => 'html', 'value' => $lead['value'], 'writable' => true, ); } return $out; } if ( isset( self::SPECS[ $node['name'] ] ) && $leaf ) { foreach ( self::SPECS[ $node['name'] ] as $key => $spec ) { list( $label, $type, $kind ) = $spec; $value = self::extract( $inner, $node, $kind ); if ( null === $value ) { continue; // e.g. an image without a caption element: nothing to edit in place } $out[] = $base + array( 'locator' => $node['path'] . '/' . $key, 'label' => "$where: $label", 'type' => $type, 'value' => $value, 'writable' => true, ); } return $out; } // Dynamic blocks (no saved HTML) render from their attributes: plain text attributes are safe to edit. if ( '' === trim( $inner ) && ! $node['children'] ) { foreach ( self::TEXT_ATTRS as $attr ) { if ( isset( $node['attrs'][ $attr ] ) && is_string( $node['attrs'][ $attr ] ) ) { $out[] = $base + array( 'locator' => $node['path'] . '/' . $attr, 'label' => "$where: " . ucfirst( $attr ), 'type' => 'text', 'value' => $node['attrs'][ $attr ], 'writable' => true, 'kind' => 'blockattr', ); } } return $out; } // Anything else with text: readable, not editable (its saved HTML is generated from structure ADI can't safely rewrite). $text = $leaf ? trim( wp_strip_all_tags( $inner ) ) : ''; if ( '' !== $text ) { $out[] = $base + array( 'locator' => $node['path'] . '/content', 'label' => $where, 'type' => 'readonly', 'value' => $text, 'writable' => false, 'note' => 'Shown for reference; edit this block in the block editor.', ); } return $out; } /** * A parent block's own text before its first child: offsets into $content plus the value. * * @return array{start:int,end:int,value:string}|null */ private static function lead( $content, array $node ) { $tag = self::LEAD[ $node['name'] ]; $segment = substr( $content, $node['inner_start'], $node['children'][0]['open_start'] - $node['inner_start'] ); if ( ! preg_match( '#^(\s*<' . $tag . '\b[^>]*>)(.*?)(\s*)\z#s', $segment, $m ) ) { return null; } $start = $node['inner_start'] + strlen( $m[1] ); return array( 'start' => $start, 'end' => $start + strlen( $m[2] ), 'value' => $m[2] ); } /** The value at $kind in a block's inner HTML, or null when that part isn't there. */ private static function extract( $inner, array $node, $kind ) { $parts = self::locate( $inner, $node, $kind ); return null === $parts ? null : $parts['value']; } /** * Find $kind in $inner: array( value, before, after ) where before . raw . after === $inner, * or for attributes/images the value only (writes go through the tag processor). */ private static function locate( $inner, array $node, $kind ) { if ( 'whole' === $kind ) { return array( 'value' => $inner, 'before' => '', 'after' => '' ); } if ( 'root' === $kind ) { if ( ! preg_match( '#^(\s*<([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*>)(.*)(\s*)\z#s', $inner, $m ) ) { return null; } return array( 'value' => $m[3], 'before' => $m[1], 'after' => $m[4] ); } if ( 0 === strpos( $kind, 'el:' ) ) { $tag = substr( $kind, 3 ); if ( preg_match_all( '#<' . $tag . '\b[^>]*>#i', $inner ) !== 1 || ! preg_match( '#^(.*?<' . $tag . '\b[^>]*>)(.*?)(.*)\z#is', $inner, $m ) ) { return null; // absent, or ambiguous (two of them): not editable in place } return array( 'value' => $m[2], 'before' => $m[1], 'after' => $m[3] ); } if ( 0 === strpos( $kind, 'attr:' ) ) { list( , $tag, $attr ) = explode( ':', $kind ); $p = new \WP_HTML_Tag_Processor( $inner ); if ( ! $p->next_tag( $tag ) ) { return null; } $value = $p->get_attribute( $attr ); return array( 'value' => is_string( $value ) ? $value : '' ); } if ( 'image' === $kind ) { return array( 'value' => isset( $node['attrs']['id'] ) ? (int) $node['attrs']['id'] : 0 ); } return null; } public function write( \WP_Post $post, $locator, $value ) { if ( ! preg_match( '#^(\d+(?:\.\d+)*)/([A-Za-z_]+)\z#', $locator, $m ) ) { throw new Tool_Error( esc_html( "gutenberg:$locator is not a block field." ) ); } $content = $post->post_content; $nodes = self::map( $post ); $node = Block_Map::find( $nodes, $m[1] ); $field = $node ? $this->read( $post, $locator ) : null; if ( ! $node || ! $field || ! $field['writable'] ) { throw new Tool_Error( esc_html( "gutenberg:$locator doesn't exist or can't be edited." ) ); } $key = $m[2]; if ( isset( $field['kind'] ) && 'blockattr' === $field['kind'] ) { list( $new ) = Block_Map::splice_attr( $content, $node, $key, $value ); } elseif ( isset( self::LEAD[ $node['name'] ] ) && $node['children'] ) { self::assert_inline( $value, self::LEAD[ $node['name'] ] ); $lead = self::lead( $content, $node ); $new = Block_Map::splice_range( $content, $lead['start'], $lead['end'], $value ); } else { $kind = self::SPECS[ $node['name'] ][ $key ][2]; $inner = Block_Map::inner( $content, $node ); $new = $this->rewrite( $content, $node, $inner, $kind, $value ); } self::assert_only_target_changed( $content, $new, $node ); self::$intended[ $post->ID ] = array( $new, $node['path'], $key ); $result = wp_update_post( wp_slash( array( 'ID' => $post->ID, 'post_content' => $new, ) ), true ); if ( is_wp_error( $result ) ) { throw new Tool_Error( esc_html( 'WordPress refused the change: ' . $result->get_error_message() ) ); } } private function rewrite( $content, array $node, $inner, $kind, $value ) { if ( 'image' === $kind ) { $size = isset( $node['attrs']['sizeSlug'] ) ? $node['attrs']['sizeSlug'] : 'full'; $src = $value ? wp_get_attachment_image_url( $value, $size ) : ''; if ( ! $value || ! $src ) { throw new Tool_Error( 'Choose an image from the Media Library to replace this one (removing images from a page is done in the block editor).' ); } if ( isset( $node['attrs']['width'] ) || isset( $node['attrs']['height'] ) || isset( $node['attrs']['aspectRatio'] ) ) { throw new Tool_Error( 'This image has a fixed size or shape set in the block editor; a different image would be stretched. Replace it in the block editor.' ); } $p = new \WP_HTML_Tag_Processor( $inner ); $dest = isset( $node['attrs']['linkDestination'] ) ? $node['attrs']['linkDestination'] : ''; if ( in_array( $dest, array( 'media', 'attachment' ), true ) ) { // The image links to its own file or attachment page: point the link at the new one. if ( ! $p->next_tag( 'a' ) ) { throw new Tool_Error( 'This image block has no link to update.' ); } $p->set_attribute( 'href', 'media' === $dest ? wp_get_attachment_url( $value ) : get_attachment_link( $value ) ); $rel = $p->get_attribute( 'rel' ); if ( is_string( $rel ) && preg_match( '/\bwp-att-\d+\b/', $rel ) ) { $p->set_attribute( 'rel', preg_replace( '/\bwp-att-\d+\b/', 'wp-att-' . $value, $rel ) ); } } if ( ! $p->next_tag( 'img' ) ) { throw new Tool_Error( 'This image block has no to replace.' ); } if ( null !== $p->get_attribute( 'width' ) || null !== $p->get_attribute( 'height' ) ) { throw new Tool_Error( 'This image has a fixed size set in its HTML; a different image would be stretched. Replace it in the block editor.' ); } $p->set_attribute( 'src', $src ); $class = (string) $p->get_attribute( 'class' ); $class = preg_match( '/\bwp-image-\d+\b/', $class ) ? preg_replace( '/\bwp-image-\d+\b/', 'wp-image-' . $value, $class ) : trim( $class . ' wp-image-' . $value ); $p->set_attribute( 'class', $class ); // The old description would now describe the wrong picture: take the new image's own alt text. $p->set_attribute( 'alt', (string) get_post_meta( $value, '_wp_attachment_image_alt', true ) ); // Inner first (it sits after the opener, so the opener's offsets stay valid), then the opener. $spliced = Block_Map::splice_inner( $content, $node, $p->get_updated_html() ); list( $final ) = Block_Map::splice_attr( $spliced, $node, 'id', $value ); return $final; } if ( 0 === strpos( $kind, 'attr:' ) ) { list( , $tag, $attr ) = explode( ':', $kind ); $p = new \WP_HTML_Tag_Processor( $inner ); $p->next_tag( $tag ); $p->set_attribute( $attr, $value ); return Block_Map::splice_inner( $content, $node, $p->get_updated_html() ); } $parts = self::locate( $inner, $node, $kind ); if ( null === $parts ) { throw new Tool_Error( 'That part of the block is no longer there; call wp_get_content again.' ); } if ( 'whole' === $kind ) { self::assert_closed( $value ); } if ( 'root' === $kind ) { preg_match( '#<([a-zA-Z][a-zA-Z0-9-]*)#', $parts['before'], $own ); self::assert_inline( $value, strtolower( $own[1] ) ); } elseif ( 0 === strpos( $kind, 'el:' ) ) { self::assert_inline( $value, substr( $kind, 3 ) ); // Nor a tag another part of this block is found by (a in a pullquote's text would // make its Citation part ambiguous, and it would vanish from the field list). foreach ( self::SPECS[ $node['name'] ] as $spec ) { if ( $spec[2] !== $kind && preg_match( '/^(?:el|attr):([a-z0-9]+)/', $spec[2], $other ) && in_array( $other[1], array_map( static function ( $t ) { return ltrim( $t, '/' ); }, \AdiBridge\Html::tag_names( $value ) ), true ) ) { throw new Tool_Error( esc_html( 'This text can\'t contain <' . $other[1] . '>: this block keeps another of its parts in that tag. Nothing was changed.' ) ); } } } return Block_Map::splice_inner( $content, $node, $parts['before'] . $value . $parts['after'] ); } /** * A block's text part holds inline content only (bold, italic, links, line breaks): a

, *

or another $own element inside it would break the block's HTML, and the editor would * reject the block as invalid even though it still parses. */ private static function assert_inline( $value, $own ) { $names = array_map( static function ( $t ) { return ltrim( $t, '/' ); }, \AdiBridge\Html::tag_names( $value ) ); $bad = array_values( array_unique( array_merge( array_diff( $names, self::INLINE_TAGS ), array_intersect( $names, array( $own ) ) ) ) ); if ( $bad ) { throw new Tool_Error( esc_html( 'This is a single block of text: send inline text only (bold, italic, links, line breaks), without <' . implode( '>, <', $bad ) . '>. To add paragraphs or sections, edit the page in the block editor.' ) ); } if ( false !== strpos( $value, '' ) ) { throw new Tool_Error( 'This is a single block of text: HTML comments () are not allowed in it — an unclosed one would hide the rest of the page.' ); } if ( ! self::balanced( $value ) ) { throw new Tool_Error( 'The formatting tags in this text are not balanced (every , , … needs its closing tag, in order). Nothing was changed.' ); } } /** * Custom HTML / shortcode blocks may hold any markup, but nothing left open: an unclosed comment * or