Visibility Diagnostics. * * @package GateForge */ namespace GateForge\Admin; if ( ! defined( 'ABSPATH' ) ) { exit; } use GateForge\Rules\Failure_Counter; use GateForge\Rules\Registry; use GateForge\Rules\Rule; use GateForge\Parser\Summarizer; use GateForge\Storage\Block_Rules; use GateForge\Storage\Settings; use GateForge\Storage\Widget_Store; /** * Prompt 1 section 10.7. Status, condition failures, registry log, the * widget-rule list, a block-rule finder (keyset pagination by post ID in * batches of 200, never OFFSET; F23), a read-only scan of the active theme's * template, part and pattern files, the blind spots stated on screen, a * page-cache warning naming only the risky conditions (F17), Copy diagnostics * with quoted literals over 20 characters redacted (F32), and the Settings tab. * States plainly that visibility is not security and that deactivating * GateForge shows everything (3.6, 3.7). Read-only except the Settings form, * which checks the capability and a nonce. */ final class Diagnostics_Page { const SLUG = 'gateforge-diagnostics'; const BATCH = 200; const REDACT_LEN = 20; /** Free conditions whose answer a page cache can freeze (device, schedule; F17). Pro's cart and cookie conditions are not known to Free yet (open point). */ const CACHE_RISKY = array( 'wp_is_mobile', 'date_between' ); /** * Hook in. */ public static function register() { add_action( 'admin_menu', array( __CLASS__, 'menu' ) ); add_action( 'admin_post_gtfg_save_settings', array( __CLASS__, 'handle_settings' ) ); add_action( 'admin_notices', array( __CLASS__, 'unchecked_notice' ) ); } /** * Menu. */ public static function menu() { add_management_page( __( 'Visibility Diagnostics', 'gateforge' ), __( 'Visibility Diagnostics', 'gateforge' ), 'edit_theme_options', self::SLUG, array( __CLASS__, 'render' ) ); } /** * Settings handler. */ public static function handle_settings() { if ( ! current_user_can( 'edit_theme_options' ) ) { wp_die( esc_html__( 'You are not allowed to do this.', 'gateforge' ), 403 ); } check_admin_referer( 'gtfg_save_settings' ); // phpcs:disable WordPress.Security.NonceVerification.Missing -- verified above. $cap = isset( $_POST['block_rule_cap'] ) ? sanitize_key( wp_unslash( $_POST['block_rule_cap'] ) ) : 'edit_posts'; $types = isset( $_POST['block_types'] ) ? sanitize_textarea_field( wp_unslash( $_POST['block_types'] ) ) : ''; $list = array(); foreach ( preg_split( '/[\s,]+/', $types ) as $t ) { if ( preg_match( '#^[a-z0-9-]+/[a-z0-9-]+$#', $t ) ) { $list[] = $t; } } Settings::update( array( 'main_query_fix' => ! empty( $_POST['main_query_fix'] ), 'delete_data_on_uninstall' => ! empty( $_POST['delete_data_on_uninstall'] ), 'block_rule_cap' => in_array( $cap, array( 'edit_posts', 'publish_posts', 'edit_others_posts', 'edit_pages', 'edit_theme_options', 'manage_options' ), true ) ? $cap : 'edit_posts', 'block_types' => $list ? $list : 'all', ) ); // phpcs:enable wp_safe_redirect( add_query_arg( array( 'page' => self::SLUG, 'tab' => 'settings', 'gtfg_msg' => 'saved', ), admin_url( 'tools.php' ) ) ); exit; } /** * Widget rules: rules on widget instances plus rules on blocks inside block * widgets, with counts of unreadable, unchecked and imported ones. * * @return array{unchecked:int, invalid:int, total:int, imported:int, block:int, rules:array, rows:array} */ public static function widget_stats() { $stats = array( 'unchecked' => 0, 'invalid' => 0, 'total' => 0, 'imported' => 0, 'block' => 0, 'rules' => array(), 'rows' => array(), ); $areas = self::widget_areas(); $add = static function ( $key, $wid, $kind, $block, Rule $rule ) use ( &$stats, $areas ) { ++$stats['total']; if ( Rule::STATE_INVALID === $rule->state ) { ++$stats['invalid']; } if ( Rule::STATE_INVALID === $rule->state || self::has_unknown( $rule->tree ) ) { ++$stats['unchecked']; } if ( is_array( $rule->import ) ) { ++$stats['imported']; } if ( 'block' === $kind ) { ++$stats['block']; } $stats['rules'][ $key ] = $rule; $stats['rows'][] = array( 'key' => $key, 'id' => $wid, 'kind' => $kind, 'block' => $block, 'area' => isset( $areas[ $wid ] ) ? $areas[ $wid ] : '', 'rule' => $rule, ); }; // Rules stored on widget instances (classic widgets and imported rules). foreach ( Widget_Store::all_rules() as $wid => $raw ) { $rule = Rule::from_stored( $raw ); if ( Rule::STATE_NONE !== $rule->state ) { $add( (string) $wid, (string) $wid, 'widget', '', $rule ); } } // Rules on blocks inside block widgets (G-5): the block widgets editor stores // them in the widget_block content, not on the instance. $blocks = get_option( 'widget_block', array() ); foreach ( is_array( $blocks ) ? $blocks : array() as $number => $inst ) { if ( ! is_int( $number ) || ! is_array( $inst ) || ! isset( $inst['content'] ) || ! is_string( $inst['content'] ) || ! Block_Rules::has_rules( $inst['content'] ) ) { continue; } $wid = 'block-' . $number; $found = array(); self::collect_named( parse_blocks( $inst['content'] ), $found ); foreach ( $found as $i => $f ) { $add( $wid . ' #' . ( $i + 1 ), $wid, 'block', $f[0], Rule::from_stored( $f[1], 'block' ) ); } } return $stats; } /** * Widget ID => widget area ID, from the stored (unfiltered) sidebars list. * * @return array */ private static function widget_areas() { $out = array(); $all = get_option( 'sidebars_widgets', array() ); foreach ( is_array( $all ) ? $all : array() as $area => $ids ) { if ( ! is_array( $ids ) ) { continue; } foreach ( $ids as $wid ) { if ( is_string( $wid ) ) { $out[ $wid ] = (string) $area; } } } return $out; } /** * Every block rule in parsed blocks with its block name, in document order. * * @param array $blocks Parsed blocks. * @param array $out Output: list of [block name, raw rule] (by reference). */ private static function collect_named( array $blocks, array &$out ) { foreach ( $blocks as $b ) { if ( isset( $b['attrs']['metadata'] ) && is_array( $b['attrs']['metadata'] ) && array_key_exists( Block_Rules::ATTR, $b['attrs']['metadata'] ) ) { $out[] = array( isset( $b['blockName'] ) ? (string) $b['blockName'] : '', $b['attrs']['metadata'][ Block_Rules::ATTR ] ); } if ( ! empty( $b['innerBlocks'] ) && is_array( $b['innerBlocks'] ) ) { self::collect_named( $b['innerBlocks'], $out ); } } } /** * Does a tree contain an unknown node. * * @param mixed $node Node. * @return bool */ public static function has_unknown( $node ) { if ( ! is_array( $node ) ) { return false; } if ( array_key_exists( 'unknown', $node ) || ( isset( $node['op'] ) && 'ref' === $node['op'] ) ) { return true; } foreach ( isset( $node['items'] ) && is_array( $node['items'] ) ? $node['items'] : array() as $c ) { if ( self::has_unknown( $c ) ) { return true; } } return isset( $node['item'] ) && self::has_unknown( $node['item'] ); } /** * Condition names used in a tree. * * @param mixed $node Node. * @param array $out Names (by reference). */ public static function cond_names( $node, array &$out ) { if ( ! is_array( $node ) ) { return; } if ( isset( $node['cond'] ) && is_string( $node['cond'] ) ) { $out[ strtolower( $node['cond'] ) ] = true; } foreach ( isset( $node['items'] ) && is_array( $node['items'] ) ? $node['items'] : array() as $c ) { self::cond_names( $c, $out ); } if ( isset( $node['item'] ) ) { self::cond_names( $node['item'], $out ); } } /** * Admin notice with the count, on GateForge screens and the widgets screen. */ public static function unchecked_notice() { $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null; if ( ! $screen || ! current_user_can( 'edit_theme_options' ) ) { return; } $ours = \GateForge\Plugin::admin_screens( array( 'widgets', 'tools_page_' . self::SLUG, 'tools_page_' . Import_Page::SLUG ) ); if ( ! in_array( $screen->id, $ours, true ) ) { return; } $stats = self::widget_stats(); if ( $stats['unchecked'] > 0 ) { echo '

' . esc_html( sprintf( /* translators: %1$d: number of widgets. */ _n( '%1$d item can be hidden because part of its rule could not be checked.', '%1$d items can be hidden because part of their rule could not be checked.', $stats['unchecked'], 'gateforge' ), $stats['unchecked'] ) ) . '

'; } $fails = get_option( Failure_Counter::OPTION, array() ); if ( is_array( $fails ) && $fails ) { echo '

' . esc_html( sprintf( /* translators: %1$s: condition names. */ __( 'These conditions failed while checking rules (items using them were hidden): %1$s. See Visibility Diagnostics.', 'gateforge' ), implode( ', ', array_map( 'strval', array_keys( $fails ) ) ) ) ) . '

'; } } /** * Block-rule finder: one keyset page (ID > $after), never OFFSET (F23). * * @param int $after Last post ID seen. * @return array{ids:array, next:int|null} */ public static function block_rule_page( $after ) { global $wpdb; $ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE ID > %d AND post_status <> 'auto-draft' AND post_content LIKE %s ORDER BY ID ASC LIMIT %d", (int) $after, '%' . $wpdb->esc_like( '"gateforgeRule"' ) . '%', self::BATCH ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- on-demand diagnostics query, no index kept (11.1). $ids = array_map( 'intval', is_array( $ids ) ? $ids : array() ); return array( 'ids' => $ids, 'next' => count( $ids ) === self::BATCH ? end( $ids ) : null, ); } /** * Read-only scan of the active theme's template, part and pattern files. * * @return array{possible:bool, found:array, scanned:int} */ public static function theme_scan() { $found = array(); $scanned = 0; $roots = array_unique( array( get_stylesheet_directory(), get_template_directory() ) ); $any = false; foreach ( $roots as $root ) { foreach ( array( 'templates', 'parts', 'patterns', 'block-templates', 'block-template-parts' ) as $sub ) { $dir = $root . '/' . $sub; if ( ! is_dir( $dir ) || ! is_readable( $dir ) ) { continue; } $any = true; $files = array_merge( (array) glob( $dir . '/*.html' ), (array) glob( $dir . '/*.php' ) ); // GLOB_BRACE is missing on some systems. foreach ( $files as $file ) { if ( ! is_string( $file ) || ! is_readable( $file ) || filesize( $file ) > 1048576 ) { continue; } ++$scanned; $text = file_get_contents( $file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- read-only local theme file. if ( is_string( $text ) && false !== strpos( $text, '"gateforgeRule"' ) ) { $found[] = str_replace( wp_normalize_path( get_theme_root() ), '', wp_normalize_path( $file ) ); } } } } return array( 'possible' => $any, 'found' => $found, 'scanned' => $scanned, ); } /** * Is a page cache evidenced. * * @return bool */ public static function page_cache_present() { return ( defined( 'WP_CACHE' ) && WP_CACHE ) || file_exists( WP_CONTENT_DIR . '/advanced-cache.php' ); } /** * Redact quoted literals longer than REDACT_LEN characters (F32). * * @param string $text Text. * @return string */ public static function redact( $text ) { $len = self::REDACT_LEN; return (string) preg_replace_callback( '/(["\'])((?:\\\\.|(?!\1).)*)\1/s', static function ( $m ) use ( $len ) { return strlen( $m[2] ) > $len ? $m[1] . '[redacted ' . strlen( $m[2] ) . ' chars]' . $m[1] : $m[0]; }, $text ); } /** * Render. */ public static function render() { if ( ! current_user_can( 'edit_theme_options' ) ) { return; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- display-only tab and paging. $tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : 'status'; echo '

' . esc_html__( 'Visibility Diagnostics', 'gateforge' ) . '

'; $base = admin_url( 'tools.php?page=' . self::SLUG ); echo ''; echo '

' . esc_html__( 'Visibility is not security. Hiding a widget or block does not protect its content; anyone who can request the page another way may still see it.', 'gateforge' ) . '

'; echo '

' . esc_html__( 'If GateForge is deactivated or deleted, its rules stop applying and every item shows. That is the only case where GateForge fails open.', 'gateforge' ) . '

'; if ( 'settings' === $tab ) { self::render_settings(); } else { self::render_status(); } echo '

' . esc_html__( 'Tip Jar', 'gateforge' ) . '

'; } /** * Settings tab. */ private static function render_settings() { $s = Settings::all(); echo '
'; wp_nonce_field( 'gtfg_save_settings' ); echo ''; echo ''; echo ''; echo ''; $types = is_array( $s['block_types'] ) ? implode( "\n", $s['block_types'] ) : ''; echo ''; echo '
' . esc_html__( 'Main query fix', 'gateforge' ) . '
' . esc_html__( 'On uninstall', 'gateforge' ) . '
' . esc_html__( 'Who may add or edit block rules', 'gateforge' ) . '
' . esc_html__( 'Block types with the rule panel', 'gateforge' ) . '

' . esc_html__( 'One block name per line. Leave empty for all block types.', 'gateforge' ) . '

'; submit_button( __( 'Save settings', 'gateforge' ) ); echo '
'; } /** * Table of every widget rule: widget, widget area, where the rule sits, summary, status. * * @param array $rows Rows from widget_stats(). */ private static function render_widget_rule_table( array $rows ) { if ( ! $rows ) { echo '

' . esc_html__( 'No widget rules found.', 'gateforge' ) . '

'; return; } echo ''; foreach ( $rows as $r ) { $rule = $r['rule']; $ok = Rule::STATE_OK === $rule->state; if ( ! $ok ) { $status = __( 'Unreadable: hidden', 'gateforge' ); } elseif ( self::has_unknown( $rule->tree ) ) { $status = __( 'Has a part that cannot be checked', 'gateforge' ); } elseif ( is_array( $rule->import ) ) { $status = __( 'Imported', 'gateforge' ); } else { $status = __( 'OK', 'gateforge' ); } if ( 'block' === $r['kind'] ) { /* translators: %1$s: block name such as core/group. */ $on = sprintf( __( 'Block inside the widget (%1$s)', 'gateforge' ), $r['block'] ); } else { $on = __( 'The widget', 'gateforge' ); } echo ''; } echo '
' . esc_html__( 'Widget', 'gateforge' ) . '' . esc_html__( 'Widget area', 'gateforge' ) . '' . esc_html__( 'Rule on', 'gateforge' ) . '' . esc_html__( 'Rule', 'gateforge' ) . '' . esc_html__( 'Status', 'gateforge' ) . '
' . esc_html( $r['id'] ) . '' . esc_html( '' !== $r['area'] ? $r['area'] : __( '(not in a widget area)', 'gateforge' ) ) . '' . esc_html( $on ) . '' . esc_html( $ok ? Summarizer::summarize( $rule->tree ) : $rule->invalid_reason ) . '' . esc_html( $status ) . '
'; } /** * Status tab. */ private static function render_status() { $stats = self::widget_stats(); echo '

' . esc_html__( 'Widget rules', 'gateforge' ) . '

'; echo '

' . esc_html( sprintf( /* translators: 1: rules, 2: imported, 3: unreadable, 4: with parts that cannot be checked. */ __( 'Rules: %1$d. Imported: %2$d. Unreadable: %3$d. With a part that cannot be checked: %4$d.', 'gateforge' ), $stats['total'], $stats['imported'], $stats['invalid'], $stats['unchecked'] ) ) . ' ' . esc_html( sprintf( /* translators: %1$d: number of rules on blocks inside block widgets. */ __( 'Of these, %1$d are on blocks inside block widgets.', 'gateforge' ), $stats['block'] ) ) . '

'; self::render_widget_rule_table( $stats['rows'] ); $deleted = array(); foreach ( $stats['rules'] as $wid => $rule ) { if ( Rule::STATE_OK === $rule->state && is_array( $rule->import ) && ! empty( $rule->import['unknown_deleted'] ) && is_array( $rule->import['unknown_deleted'] ) ) { foreach ( $rule->import['unknown_deleted'] as $entry ) { $deleted[] = array( (string) $wid, is_array( $entry ) && isset( $entry['text'] ) ? (string) $entry['text'] : '', is_array( $entry ) && isset( $entry['at'] ) ? (string) $entry['at'] : '' ); } } } echo '

' . esc_html__( 'Deleted parts that could not be checked', 'gateforge' ) . '

'; if ( $deleted ) { echo '
    '; foreach ( $deleted as $d ) { /* translators: 1: widget ID, 2: original text that was deleted, 3: date (UTC). */ echo '
  • ' . esc_html( sprintf( __( '%1$s: deleted "%2$s" on %3$s (UTC)', 'gateforge' ), $d[0], $d[1], $d[2] ) ) . '
  • '; } echo '
'; } else { echo '

' . esc_html__( 'None.', 'gateforge' ) . '

'; } $names = array(); foreach ( $stats['rules'] as $rule ) { if ( Rule::STATE_OK === $rule->state ) { self::cond_names( $rule->tree, $names ); } } $risky = array_values( array_intersect( self::CACHE_RISKY, array_keys( $names ) ) ); if ( $risky && self::page_cache_present() ) { echo '

' . esc_html( sprintf( /* translators: %1$s: condition names. */ __( 'A page cache is active. Rules using these conditions can show a cached answer to the wrong visitor or at the wrong time: %1$s. Exclude those pages from the cache or rely on rules that are the same for every visitor.', 'gateforge' ), implode( ', ', $risky ) ) ) . '

'; } $fails = get_option( Failure_Counter::OPTION, array() ); echo '

' . esc_html__( 'Condition failures', 'gateforge' ) . '

'; if ( is_array( $fails ) && $fails ) { echo '
    '; foreach ( $fails as $name => $f ) { echo '
  • ' . esc_html( (string) $name ) . ' ' . esc_html( sprintf( /* translators: 1: last date, 2: number of days with failures. */ __( 'last failed %1$s, on %2$d days', 'gateforge' ), isset( $f['date'] ) ? (string) $f['date'] : '', isset( $f['days'] ) ? (int) $f['days'] : 0 ) ) . '
  • '; } echo '
'; } else { echo '

' . esc_html__( 'None recorded.', 'gateforge' ) . '

'; } echo '

' . esc_html__( 'Condition registry', 'gateforge' ) . '

'; $log = Registry::instance()->log(); echo '

' . esc_html( sprintf( /* translators: %1$d: number of conditions. */ __( '%1$d conditions registered.', 'gateforge' ), count( Registry::instance()->all() ) ) ) . '

'; if ( $log ) { echo '
    '; foreach ( $log as $e ) { echo '
  • ' . esc_html( $e['name'] ) . ': ' . esc_html( $e['reason'] ) . '
  • '; } echo '
'; } echo '

' . esc_html__( 'Block rules', 'gateforge' ) . '

'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only paging cursor. $after = isset( $_GET['after'] ) ? absint( $_GET['after'] ) : 0; $page = self::block_rule_page( $after ); if ( $page['ids'] ) { echo ''; if ( null !== $page['next'] ) { echo '

' . esc_html__( 'Next 200', 'gateforge' ) . '

'; } } else { echo '

' . esc_html__( 'No block rules found in post content.', 'gateforge' ) . '

'; } $theme = self::theme_scan(); if ( ! $theme['possible'] ) { echo '

' . esc_html__( 'The active theme has no template, part or pattern folders that could be read, so theme files were not scanned.', 'gateforge' ) . '

'; } elseif ( $theme['found'] ) { echo '

' . esc_html__( 'Block rules found in theme files:', 'gateforge' ) . '

    '; foreach ( $theme['found'] as $f ) { echo '
  • ' . esc_html( $f ) . '
  • '; } echo '
'; } else { echo '

' . esc_html( sprintf( /* translators: %1$d: number of theme files. */ __( 'No block rules found in %1$d theme files.', 'gateforge' ), $theme['scanned'] ) ) . '

'; } echo '

' . esc_html__( 'Blind spots: this screen cannot see rules in theme-file templates, parts or patterns beyond the scan above, patterns registered in PHP, unsaved Customizer changesets, or content stored by page builders in post meta.', 'gateforge' ) . '

'; echo '

' . esc_html__( 'Copy diagnostics', 'gateforge' ) . '

'; echo '

' . esc_html( sprintf( /* translators: %1$d: character limit. */ __( 'Quoted text longer than %1$d characters is replaced with a placeholder before you copy it.', 'gateforge' ), self::REDACT_LEN ) ) . '

'; echo ''; } /** * Plain-text diagnostics. * * @param array $stats Widget stats. * @param mixed $fails Failures. * @return string */ public static function copy_text( array $stats, $fails ) { global $wp_version; $lines = array(); $lines[] = 'GateForge ' . GATEFORGE_VERSION . ', WordPress ' . $wp_version . ', PHP ' . PHP_VERSION; $lines[] = 'Rules ' . $stats['total'] . ', imported ' . $stats['imported'] . ', unreadable ' . $stats['invalid'] . ', unchecked parts ' . $stats['unchecked']; $lines[] = 'Settings ' . wp_json_encode( Settings::all() ); $lines[] = 'Failures ' . wp_json_encode( is_array( $fails ) ? $fails : array() ); foreach ( $stats['rules'] as $wid => $rule ) { $lines[] = $wid . ': ' . ( Rule::STATE_OK === $rule->state ? \GateForge\Parser\Printer::print_tree( $rule->tree ) : 'unreadable (' . $rule->invalid_reason . ')' ); } return implode( "\n", $lines ); } }