array() ); $prev = ''; foreach ( parse_blocks( (string) $existing ) as $block ) { if ( empty( $block['blockName'] ) ) { continue; } $key = (string) ( $block['attrs']['metadata']['rooster']['key'] ?? '' ); if ( '' !== $key && ! isset( $blocks[ $key ] ) ) { $stored = (string) ( $block['attrs']['metadata']['rooster']['hash'] ?? '' ); $blocks[ $key ] = array( 'block' => $block, 'stored' => $stored, 'edited' => '' === $stored || AIEO_Content_Blocks::hash( $block ) !== $stored, ); $followers[ $key ] = array(); $prev = $key; continue; } $followers[ $prev ][] = $block; } $actions = array(); $conflicts = array(); $kept = array(); $out = array(); $order = array_keys( $followers ); foreach ( $blocks as $key => $entry ) { if ( isset( $compiled[ $key ] ) ) { continue; } if ( $entry['edited'] ) { $actions[ $key ] = 'kept'; $kept[] = $key; $i = array_search( $key, $order, true ); $anchor = ''; for ( $j = (int) $i - 1; $j >= 0; $j-- ) { if ( isset( $compiled[ $order[ $j ] ] ) || '' === $order[ $j ] ) { $anchor = $order[ $j ]; break; } } $followers[ $anchor ] = array_merge( $followers[ $anchor ], array( $entry['block'] ), $followers[ $key ] ); } else { $actions[ $key ] = 'remove'; $i = array_search( $key, $order, true ); $anchor = ''; for ( $j = (int) $i - 1; $j >= 0; $j-- ) { if ( isset( $compiled[ $order[ $j ] ] ) || '' === $order[ $j ] ) { $anchor = $order[ $j ]; break; } } $followers[ $anchor ] = array_merge( $followers[ $anchor ], $followers[ $key ] ); } unset( $followers[ $key ] ); } foreach ( $followers[''] as $block ) { $out[] = AIEO_Content_Blocks::serialize($block ); } foreach ( $compiled as $key => $markup ) { $key = (string) $key; if ( ! isset( $blocks[ $key ] ) ) { $actions[ $key ] = 'create'; $out[] = $markup; } else { $entry = $blocks[ $key ]; $new = AIEO_Content_Blocks::hash( $markup ); $changed = $new !== $entry['stored']; if ( ! $entry['edited'] ) { $actions[ $key ] = $changed ? 'update' : 'unchanged'; $out[] = $changed ? $markup : AIEO_Content_Blocks::serialize($entry['block'] ); } elseif ( ! $changed ) { $actions[ $key ] = 'keep'; $out[] = AIEO_Content_Blocks::serialize($entry['block'] ); } elseif ( $force_all || in_array( $key, $force_keys, true ) ) { $actions[ $key ] = 'update'; $out[] = $markup; } else { $actions[ $key ] = 'conflict'; $conflicts[] = $key; $out[] = AIEO_Content_Blocks::serialize($entry['block'] ); } } foreach ( $followers[ $key ] ?? array() as $block ) { $out[] = AIEO_Content_Blocks::serialize($block ); } } return array( 'content' => implode( "\n\n", $out ), 'actions' => $actions, 'conflicts' => $conflicts, 'kept' => $kept ); } }