, splits it into "ours" (everything between our HTML markers) and * "theirs", and then — surface by surface — deletes whichever copy does not own * that surface. The result is exactly one canonical, one description and one * set of social tags, whoever wrote them. * * @package AiRankSuite */ declare(strict_types=1); namespace AiRankSuite\Modules\Coexistence\Services; if ( ! defined( 'ABSPATH' ) ) { exit; } final class HeadArbiter { public const OPEN = ''; public const CLOSE = ''; /** * Surfaces the arbiter can police, with the pattern that finds them. * * Every pattern is anchored on a complete tag so a partial match can never * leave a dangling fragment in the head. * * @return array */ public static function surfaces(): array { return array( 'description' => array( 'label' => __( 'Meta description', 'ai-rank-suite' ), 'pattern' => '#]*name=["\']description["\'][^>]*>\s*#i', 'desc' => __( 'The one-sentence summary search engines and AI assistants quote.', 'ai-rank-suite' ), ), 'canonical' => array( 'label' => __( 'Canonical URL', 'ai-rank-suite' ), 'pattern' => '#]*rel=["\']canonical["\'][^>]*>\s*#i', 'desc' => __( 'Two canonicals on one page make Google discard both.', 'ai-rank-suite' ), ), 'robots' => array( 'label' => __( 'Robots meta', 'ai-rank-suite' ), 'pattern' => '#]*name=["\']robots["\'][^>]*>\s*#i', 'desc' => __( 'index/noindex directives. Conflicting copies are read as the most restrictive.', 'ai-rank-suite' ), ), 'open_graph' => array( 'label' => __( 'Open Graph', 'ai-rank-suite' ), 'pattern' => '#]*property=["\']og:[^"\']*["\'][^>]*>\s*#i', 'desc' => __( 'Facebook, LinkedIn, WhatsApp and Slack link previews.', 'ai-rank-suite' ), ), 'twitter' => array( 'label' => __( 'Twitter/X cards', 'ai-rank-suite' ), 'pattern' => '#]*name=["\']twitter:[^"\']*["\'][^>]*>\s*#i', 'desc' => __( 'The card X renders when your page is shared.', 'ai-rank-suite' ), ), 'schema' => array( 'label' => __( 'Structured data', 'ai-rank-suite' ), 'pattern' => '#]*type=["\']application/ld\+json["\'][^>]*>.*?\s*#is', 'desc' => __( 'JSON-LD. Duplicate @graph blocks compete for the same rich result.', 'ai-rank-suite' ), ), 'hreflang' => array( 'label' => __( 'hreflang', 'ai-rank-suite' ), 'pattern' => '#]*hreflang=["\'][^"\']*["\'][^>]*>\s*#i', 'desc' => __( 'Language and region alternates for international sites.', 'ai-rank-suite' ), ), ); } /** * @param array $ownership surface => airs|other|both */ public function __construct( private array $ownership ) {} /** * The buffer nesting level our own ob_start() created, or 0 for none. * * Checking `ob_get_level() > 0` in finish() is not the same question. The * theme, a caching plugin or WordPress itself may have a buffer open, and * if our start() never ran — an early return, or a Throwable swallowed by * the hook guard — then closing "the" buffer means closing *theirs*, and * the entire page below the head disappears. Recording the level we opened * makes the pairing explicit: we only ever close what we opened. */ private int $level = 0; /** * Start buffering the head. Registered at a priority below everything else. */ public function start(): void { if ( is_admin() || is_feed() || wp_doing_ajax() ) { return; } if ( ob_start() ) { $this->level = ob_get_level(); // If nothing between wp_head's first and last priority ever // reaches finish() — a fatal in another plugin's head callback, // an exit() in a redirect — the buffer must still be closed, or // the page ends with its head swallowed. Shutdown is the last // point where that can be done. add_action( 'shutdown', array( $this, 'finish' ), 0 ); } } /** * Close the buffer and arbitrate. * * The buffer this opened is closed here, whatever else has happened in * between. A buffer that another component opened *above* ours and never * closed used to make this method give up and return, which left our own * ob_start() open for the rest of the request — exactly the misaligned * stack the directory's review warns about. Those foreign buffers are * flushed through first now (their content is passed on untouched), then * ours is taken. If ours is already gone, somebody below us closed it and * there is nothing to arbitrate. */ public function finish(): void { if ( 0 === $this->level ) { return; } $level = $this->level; $this->level = 0; remove_action( 'shutdown', array( $this, 'finish' ), 0 ); while ( ob_get_level() > $level ) { if ( ! ob_end_flush() ) { break; } } if ( ob_get_level() !== $level ) { return; } $head = (string) ob_get_clean(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Already-escaped head markup, filtered. echo $this->arbitrate( $head ); } /** * Split, prune, reassemble. Pure string work so it is unit-testable and * cannot touch the database. */ public function arbitrate( string $head ): string { $open = strpos( $head, self::OPEN ); $close = strpos( $head, self::CLOSE ); // Nothing of ours in this head — only foreign tags to consider, and we // have nothing to replace them with, so leave the page untouched. if ( false === $open || false === $close || $close < $open ) { return $head; } $before = substr( $head, 0, $open ); $ours = substr( $head, $open, $close - $open + strlen( self::CLOSE ) ); $after = substr( $head, $close + strlen( self::CLOSE ) ); $theirs = $before . "\x00SPLIT\x00" . $after; foreach ( self::surfaces() as $id => $def ) { $owner = $this->ownership[ $id ] ?? 'airs'; if ( 'both' === $owner ) { continue; } if ( 'airs' === $owner ) { /* * Owning a surface is not the same as having written it. * * A site with no tagline and no home description gives us * nothing to emit for the home page. Stripping the other * plugin's copy anyway turned one description into none — we * took ownership of a surface and then left it empty, which is * worse for the page than the duplicate we were fixing. * * So: only remove theirs where ours actually exists. The * result is still exactly one of each, which is the whole * promise; it is simply theirs on the surfaces we had nothing * to say about. */ if ( ! preg_match( $def['pattern'], $ours ) ) { continue; } $theirs = (string) preg_replace( $def['pattern'], '', $theirs ); } else { $ours = (string) preg_replace( $def['pattern'], '', $ours ); } } $parts = explode( "\x00SPLIT\x00", $theirs, 2 ); return ( $parts[0] ?? '' ) . $ours . ( $parts[1] ?? '' ); } /** * Count how many copies of each surface a rendered page contains. * Used by the live conflict scan so the customer sees proof, not a promise. * * @return array */ public static function census( string $html ): array { $open = strpos( $html, self::OPEN ); $close = strpos( $html, self::CLOSE ); $ours = ''; $rest = $html; if ( false !== $open && false !== $close && $close > $open ) { $ours = substr( $html, $open, $close - $open + strlen( self::CLOSE ) ); $rest = substr( $html, 0, $open ) . substr( $html, $close + strlen( self::CLOSE ) ); } $out = array(); foreach ( self::surfaces() as $id => $def ) { $a = preg_match_all( $def['pattern'], $ours ); $b = preg_match_all( $def['pattern'], $rest ); $out[ $id ] = array( 'ours' => is_int( $a ) ? $a : 0, 'theirs' => is_int( $b ) ? $b : 0, ); } return $out; } }