settings = $settings; $this->history = $history; } /** * Registers hooks. * * @return void */ public function register(): void { add_filter( 'wp_robots', array( $this, 'add_robots' ), PHP_INT_MAX ); add_filter( 'wp_headers', array( $this, 'add_headers' ) ); } /** * Returns the directives that are switched on. * * @return string[] Directive tokens. */ public function get_directives(): array { if ( aiblackout_is_disabled() ) { return array(); } $directives = array(); if ( $this->settings->get_declaration( 'noai', false ) ) { $directives[] = 'noai'; } if ( $this->settings->get_declaration( 'noimageai', false ) ) { $directives[] = 'noimageai'; } return $directives; } /** * Whether anything is being declared. * * @return bool True when at least one directive is on. */ public function is_enabled(): bool { return ! empty( $this->get_directives() ); } /** * Adds the directives to the page's robots meta tag. * * @param array $robots Directives assembled so far, keyed by directive. * @return array Filtered directives. */ public function add_robots( $robots ): array { $robots = is_array( $robots ) ? $robots : array(); $directives = $this->get_directives(); if ( empty( $directives ) || is_admin() ) { return $robots; } foreach ( $directives as $directive ) { $robots[ $directive ] = true; } return $robots; } /** * Adds the X-Robots-Tag header to front-end responses. * * @param array $headers Response headers. * @return array Filtered headers. */ public function add_headers( $headers ): array { $headers = is_array( $headers ) ? $headers : array(); $directives = $this->get_directives(); if ( empty( $directives ) || is_admin() ) { return $headers; } $existing = isset( $headers['X-Robots-Tag'] ) ? trim( (string) $headers['X-Robots-Tag'] ) : ''; if ( '' !== $existing ) { $directives = array_merge( array( $existing ), $directives ); } $headers['X-Robots-Tag'] = implode( ', ', $directives ); return $headers; } /** * Records the current declaration in the history log. * * @return void */ public function record(): void { $directives = $this->get_directives(); $this->history->record( self::TYPE, empty( $directives ) ? __( 'noai and noimageai directives withdrawn.', 'ai-blackout' ) : sprintf( /* translators: %s: Comma-separated directive names. */ __( 'Publishing the %s directive(s) in page markup and HTTP headers.', 'ai-blackout' ), implode( ', ', $directives ) ), $directives ); } }