'/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i', 'ipv4' => '/\b\d{1,3}(?:\.\d{1,3}){3}\b/', 'ipv6' => '/\b[0-9a-f]{0,4}(?::[0-9a-f]{0,4}){2,7}\b/i', 'creditcard' => '/\b(?:\d[ -]*?){13,16}\b/', ); /** * Create the site reader with its settings dependency. * * @param SettingsRepository $settings Settings repository. */ public function __construct( private SettingsRepository $settings ) { } /** * Check whether an option name is allowlisted for reading. * * @param string $name Option name. */ private function is_allowed_option( string $name ): bool { if ( in_array( $name, self::OPTION_ALLOWLIST, true ) ) { return true; } foreach ( self::OPTION_PREFIX_ALLOWLIST as $prefix ) { if ( str_starts_with( $name, $prefix ) ) { return true; } } return false; } /** * Decode a cursor offset used for paginated resources. * * @param string $cursor Encoded cursor. */ private function decode_cursor_offset( string $cursor ): int { if ( '' === $cursor ) { return 0; } // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- Cursor pagination stores a compact JSON offset. $decoded = base64_decode( $cursor, true ); if ( ! is_string( $decoded ) || '' === $decoded ) { return 0; } $state = json_decode( $decoded, true ); if ( ! is_array( $state ) || ! isset( $state['offset'] ) || ! is_numeric( $state['offset'] ) ) { return 0; } return max( 0, (int) $state['offset'] ); } /** * Sanitize option values before returning them to the assistant. * * @param string $name Option name. * @param mixed $value Raw option value. * * @return mixed */ private function sanitize_option_value( string $name, $value ) { if ( is_string( $value ) ) { if ( str_contains( $name, 'email' ) ) { return '[redacted-email]'; } if ( str_contains( $name, 'address' ) ) { return '[redacted-address]'; } } return is_scalar( $value ) ? $value : wp_json_encode( $value ); } /** * Redact sensitive values from a debug log line. * * @param string $text Raw log line. */ private function sanitize_log_text( string $text ): string { return Redactor::redact( $text ); } /** * Normalize preview text for HTTP and diagnostic responses. * * @param string $text Raw preview text. * @param int $max_chars Maximum characters to keep. */ private function normalize_http_preview_text( string $text, int $max_chars = 1200 ): string { $text = preg_replace( '/\s+/u', ' ', trim( $text ) ); if ( ! is_string( $text ) || '' === $text ) { return ''; } if ( function_exists( 'mb_substr' ) && function_exists( 'mb_strlen' ) ) { if ( mb_strlen( $text ) > $max_chars ) { return mb_substr( $text, 0, $max_chars ) . '…'; } return $text; } if ( strlen( $text ) > $max_chars ) { return substr( $text, 0, $max_chars ) . '…'; } return $text; } /** * Keep only allowlisted response headers for diagnostic output. * * @param array $headers Response headers. */ private function filter_http_headers( array $headers ): array { $allowlist = array( 'content-type', 'cache-control', 'last-modified', 'etag', 'vary', 'allow', 'location', 'link', 'x-robots-tag', 'x-cache', 'x-cache-group', 'cf-cache-status', 'access-control-allow-origin', 'access-control-allow-headers', 'access-control-expose-headers', 'content-encoding', ); $out = array(); foreach ( $allowlist as $key ) { if ( array_key_exists( $key, $headers ) ) { $out[ $key ] = $headers[ $key ]; } } return $out; } /** * Determine whether an array uses contiguous numeric keys. * * @param array $value Candidate array. */ private function is_list_array( array $value ): bool { return array_keys( $value ) === range( 0, count( $value ) - 1 ); } /** * Summarize arbitrary JSON-like data for compact diagnostics. * * @param mixed $value Input value. * @param int $depth Current recursion depth. * * @return mixed */ private function summarize_json_value( $value, int $depth = 0 ) { if ( $depth >= 2 ) { if ( is_array( $value ) ) { return array( 'type' => $this->is_list_array( $value ) ? 'list' : 'object' ); } if ( is_string( $value ) ) { return $this->normalize_http_preview_text( Redactor::redact( $value ), 160 ); } return $value; } if ( is_array( $value ) ) { if ( $this->is_list_array( $value ) ) { $summary = array( 'type' => 'list', 'count' => count( $value ), ); if ( ! empty( $value ) ) { $summary['first_item'] = $this->summarize_json_value( $value[0], $depth + 1 ); } return $summary; } $summary = array( 'type' => 'object', 'keys' => array_slice( array_values( array_map( 'strval', array_keys( $value ) ) ), 0, 15 ), ); $scalar_preview = array(); foreach ( $value as $key => $item ) { if ( count( $scalar_preview ) >= 8 ) { break; } if ( is_scalar( $item ) || null === $item ) { $scalar_preview[ (string) $key ] = is_string( $item ) ? $this->normalize_http_preview_text( Redactor::redact( $item ), 160 ) : $item; } } if ( ! empty( $scalar_preview ) ) { $summary['fields'] = $scalar_preview; } return $summary; } if ( is_string( $value ) ) { return $this->normalize_http_preview_text( Redactor::redact( $value ), 160 ); } return $value; } /** * Build a compact summary of an HTTP response body. * * @param string $body Raw response body. * @param string $content_type Response content type. */ private function summarize_http_body( string $body, string $content_type ): array { $body = (string) $body; if ( '' === $body ) { return array( 'body_kind' => 'empty', 'body_preview' => '', 'truncated' => false, ); } $is_textish = ( false !== stripos( $content_type, 'text/' ) ) || ( false !== stripos( $content_type, 'json' ) ) || ( false !== stripos( $content_type, 'xml' ) ) || ( false !== stripos( $content_type, 'javascript' ) ); if ( ! $is_textish || preg_match( '/[^\P{C}\t\r\n]/u', $body ) ) { return array( 'body_kind' => 'binary', 'body_preview' => '', 'truncated' => true, ); } if ( false !== stripos( $content_type, 'json' ) ) { $decoded = json_decode( $body, true ); if ( null !== $decoded || 'null' === trim( $body ) ) { return array( 'body_kind' => 'json', 'body_summary' => $this->summarize_json_value( $decoded ), 'truncated' => false, ); } } if ( false !== stripos( $content_type, 'html' ) ) { $title = ''; if ( preg_match( '/]*>(.*?)<\/title>/is', $body, $match ) ) { $title = $this->normalize_http_preview_text( wp_strip_all_tags( html_entity_decode( $match[1], ENT_QUOTES ) ), 200 ); } $text = $this->normalize_http_preview_text( Redactor::redact( wp_strip_all_tags( $body ) ), 1200 ); $summary = array( 'body_kind' => 'html', 'body_preview' => $text, 'truncated' => strlen( $body ) > 1200, ); if ( '' !== $title ) { $summary['body_summary'] = array( 'title' => $title ); } return $summary; } $preview = $this->normalize_http_preview_text( Redactor::redact( $body ), 1200 ); return array( 'body_kind' => false !== stripos( $content_type, 'xml' ) ? 'xml' : 'text', 'body_preview' => $preview, 'truncated' => strlen( $body ) > 1200, ); } /** * Trim a site health explanation down to a short readable sentence. * * @param string $description Full site health description. * @param int $max_chars Maximum characters to keep. */ private function trim_site_health_reason( string $description, int $max_chars = 220 ): string { $description = html_entity_decode( $description, ENT_QUOTES | ENT_HTML5, 'UTF-8' ); $description = preg_replace( '/<[^>]+>/', ' ', $description ); $description = preg_replace( '/\s+/u', ' ', trim( (string) $description ) ); if ( ! is_string( $description ) || '' === $description ) { return ''; } $slice = static function ( string $text, int $start, ?int $length = null ): string { if ( function_exists( 'mb_substr' ) ) { return null === $length ? mb_substr( $text, $start ) : mb_substr( $text, $start, $length ); } return null === $length ? substr( $text, $start ) : substr( $text, $start, $length ); }; $length = static function ( string $text ): int { if ( function_exists( 'mb_strlen' ) ) { return mb_strlen( $text ); } return strlen( $text ); }; if ( $length( $description ) <= $max_chars ) { return $description; } $window = $slice( $description, 0, min( $length( $description ), $max_chars + 40 ) ); if ( preg_match_all( '/[.!?](?:\s|$)/u', $window, $matches, PREG_OFFSET_CAPTURE ) ) { $best_offset = null; foreach ( $matches[0] as $match ) { $byte_offset = (int) $match[1] + 1; $offset = function_exists( 'mb_strlen' ) ? mb_strlen( substr( $window, 0, $byte_offset ), 'UTF-8' ) : $byte_offset; if ( $offset <= $max_chars + 1 && $offset >= (int) floor( $max_chars * 0.6 ) ) { $best_offset = $offset; } } if ( null !== $best_offset ) { return rtrim( $slice( $window, 0, $best_offset ) ); } } $candidate = $slice( $description, 0, $max_chars ); if ( preg_match( '/^(.+)\s+\S*$/u', $candidate, $matches ) ) { $candidate = $matches[1]; } return rtrim( $candidate, " \t\n\r\0\x0B.,;:!?" ) . '…'; } /** * Translate file access denial reasons into user-facing messages. * * @param string $reason Policy denial reason. */ private function files_path_error_message( string $reason ): string { return match ( $reason ) { 'missing_scope' => 'Provide filter.scope for files.', 'invalid_scope' => 'Files scope must be one of theme, upload, mu_plugin, plugin_manifest, or dropin.', 'missing_target' => 'Provide filter.target for this files scope.', 'missing_relative_path' => 'Provide filter.relative_path for this files scope.', 'scope_unavailable' => 'The requested files scope is not available on this site.', 'target_not_found' => 'The requested theme, plugin, MU plugin, or drop-in could not be found.', 'not_found_or_unreadable' => 'The requested file does not exist or is not readable.', 'invalid_relative_path' => 'The requested relative path could not be resolved inside the allowed scope.', 'sensitive_path' => 'Path points to a blocked sensitive file or directory.', default => 'Path is not allowed by the file access policy.', }; } /** * Normalize a log line so repeated events can be grouped. * * @param string $line Sanitized log line. */ private function normalize_log_signature( string $line ): string { $normalized = preg_replace( '/^\[[^\]]+\]\s*/', '', $line ); $normalized = preg_replace( '/^\d{4}-\d{2}-\d{2}[T\s][0-9:.+-Z]+\s*/', '', (string) $normalized ); $normalized = preg_replace( '/\s+/', ' ', trim( (string) $normalized ) ); return is_string( $normalized ) ? $normalized : $line; } /** * Deduplicate noisy log lines while preserving a short repetition summary. * * @param array $lines Sanitized log lines. */ private function dedupe_log_lines( array $lines ): array { $out = array(); $seen = array(); $max_preserved_per_signature = 3; foreach ( $lines as $line ) { $signature = $this->normalize_log_signature( (string) $line ); if ( '' === $signature ) { continue; } if ( isset( $seen[ $signature ] ) ) { $entry = &$seen[ $signature ]; ++$entry['count']; if ( $entry['count'] <= $max_preserved_per_signature ) { $out[] = array( 'line' => (string) $line, 'count' => 1, ); } continue; } $seen[ $signature ] = array( 'count' => 1, 'first_index' => count( $out ), ); $out[] = array( 'line' => (string) $line, 'count' => 1, ); } foreach ( $seen as $signature => $entry ) { if ( (int) $entry['count'] <= $max_preserved_per_signature ) { continue; } $out[] = array( 'line' => sprintf( '%s [repeated %dx beyond the first %d]', $out[ $entry['first_index'] ]['line'], (int) $entry['count'] - $max_preserved_per_signature, $max_preserved_per_signature ), 'count' => 1, ); } return array_map( static function ( array $row ): string { return $row['count'] > 1 ? sprintf( '%s [repeated %dx]', $row['line'], (int) $row['count'] ) : $row['line']; }, $out ); } /** * Inspect autoloaded transient metadata without enumerating all transients. * * @param int $limit Maximum rows to return. * @param array $meta Response metadata, updated by reference. */ private function load_transient_metadata( int $limit, array &$meta = array() ): array { $alloptions = wp_load_alloptions(); if ( ! is_array( $alloptions ) ) { $alloptions = array(); } $rows = array(); $counts = array( 'autoloaded_single' => 0, 'autoloaded_site' => 0, ); $sources = array( array( 'prefix' => '_transient_', 'timeout_prefix' => '_transient_timeout_', 'type' => 'single', 'timeout_getter' => static fn( string $key ) => get_option( $key, null ), ), array( 'prefix' => '_site_transient_', 'timeout_prefix' => '_site_transient_timeout_', 'type' => 'site', 'timeout_getter' => is_multisite() ? static fn( string $key ) => get_site_option( $key, null ) : static fn( string $key ) => get_option( $key, null ), ), ); foreach ( $alloptions as $option_name => $option_value ) { $option_name = (string) $option_name; foreach ( $sources as $source ) { if ( ! str_starts_with( $option_name, $source['prefix'] ) || str_starts_with( $option_name, $source['timeout_prefix'] ) ) { continue; } $base = substr( $option_name, strlen( $source['prefix'] ) ); if ( '' === $base ) { continue; } $timeout_key = $source['timeout_prefix'] . $base; $timeout = call_user_func( $source['timeout_getter'], $timeout_key ); $size_kb = (int) round( strlen( (string) maybe_serialize( $option_value ) ) / 1024 ); if ( 'single' === $source['type'] ) { ++$counts['autoloaded_single']; } else { ++$counts['autoloaded_site']; } $rows[] = array( 'type' => $source['type'], 'key_hash' => substr( sha1( $base ), 0, 12 ), 'size_kb' => $size_kb, 'expires' => is_numeric( $timeout ) ? (int) $timeout : null, 'expires_iso' => is_numeric( $timeout ) ? gmdate( 'c', (int) $timeout ) : null, ); break; } } $rows = array_values( array_filter( $rows, static fn( array $row ): bool => (int) ( $row['size_kb'] ?? 0 ) > 0 ) ); usort( $rows, static fn( array $a, array $b ): int => (int) $b['size_kb'] <=> (int) $a['size_kb'] ); $meta['summary'] = array_merge( isset( $meta['summary'] ) && is_array( $meta['summary'] ) ? $meta['summary'] : array(), array( 'autoloaded_single_count' => $counts['autoloaded_single'], 'autoloaded_site_count' => $counts['autoloaded_site'], 'scan_scope' => 'autoloaded_transients_only', ) ); $meta['note'] = 'Transient inspection is limited to autoloaded transient metadata in strict-safe mode; non-autoloaded transients are not enumerated.'; return array_slice( $rows, 0, $limit ); } /** * Convert a Unix timestamp to an ISO8601 string. * * @param int|null $timestamp Unix timestamp. */ private function timestamp_to_iso( ?int $timestamp ): ?string { if ( ! is_int( $timestamp ) || $timestamp <= 0 ) { return null; } return gmdate( 'c', $timestamp ); } /** * Load common wp-admin dependencies used by WP_Site_Health tests when * running outside classic wp-admin pages (e.g. REST context). * * These ABSPATH-based includes load WordPress core admin helpers on demand so * the plugin can call existing core APIs from a REST request. They are not * used to discover plugin-owned storage or to create writable filesystem * paths. */ private function ensure_site_health_dependencies_loaded(): void { $admin_includes = array( ABSPATH . 'wp-admin/includes/update.php', ABSPATH . 'wp-admin/includes/plugin.php', ABSPATH . 'wp-admin/includes/theme.php', ABSPATH . 'wp-admin/includes/misc.php', ); foreach ( $admin_includes as $file ) { if ( file_exists( $file ) ) { require_once $file; } } } /** * Execute a Site Health test via its callback without touching private WP core APIs. * * @param WP_Site_Health $health Site health instance. * @param mixed $callback Callback reference from get_tests(). * @param string|null $test_id Fallback test identifier. * * @return mixed */ private function run_site_health_test( WP_Site_Health $health, $callback, ?string $test_id = null ) { if ( is_array( $callback ) ) { if ( isset( $callback[0] ) && is_string( $callback[0] ) && 'WP_Site_Health' === $callback[0] ) { $callback[0] = $health; } if ( is_callable( $callback ) ) { return call_user_func( $callback ); } } if ( is_callable( $callback ) ) { return call_user_func( $callback ); } if ( is_string( $callback ) ) { if ( method_exists( $health, $callback ) ) { return $health->{$callback}(); } $prefixed = 'get_test_' . str_replace( '-', '_', $callback ); if ( method_exists( $health, $prefixed ) ) { return $health->{$prefixed}(); } if ( function_exists( $callback ) ) { return call_user_func( $callback ); } } if ( is_string( $test_id ) && '' !== $test_id ) { $by_id = 'get_test_' . str_replace( '-', '_', $test_id ); if ( method_exists( $health, $by_id ) ) { return $health->{$by_id}(); } } return null; } /** * Describe a callback without leaking implementation details. * * @param mixed $callback Callback reference. */ private function describe_callback( $callback ): array { $type = 'unknown'; $hint = ''; if ( is_string( $callback ) ) { $type = str_contains( $callback, '::' ) ? 'static' : 'function'; $hint = substr( sha1( $callback ), 0, 12 ); } elseif ( is_array( $callback ) ) { $type = 'method'; $target = is_object( $callback[0] ) ? get_class( $callback[0] ) : (string) $callback[0]; $hint = substr( sha1( $target . '::' . ( $callback[1] ?? '' ) ), 0, 12 ); } elseif ( $callback instanceof \Closure ) { $type = 'closure'; $hint = substr( spl_object_hash( $callback ), -12 ); } elseif ( is_object( $callback ) && method_exists( $callback, '__invoke' ) ) { $type = 'invokable'; $hint = substr( sha1( get_class( $callback ) ), 0, 12 ); } return array( 'type' => $type, 'hash' => $hint, ); } /** * Handle the read-only diagnostics REST request. * * @param WP_REST_Request $request Current REST request. */ public function handle( WP_REST_Request $request ): WP_REST_Response { $__t0 = microtime( true ); // ---- Validate base args $resource = is_string( $request['resource'] ) ? $request['resource'] : ''; $filter = is_array( $request['filter'] ) ? $request['filter'] : array(); $limit = isset( $request['limit'] ) ? (int) $request['limit'] : 50; $cursor = is_string( $request['cursor'] ) ? $request['cursor'] : ''; if ( $limit < 1 ) { $limit = 1; } if ( $limit > 200 ) { $limit = 200; } try { $meta = array(); $data = array(); $next = null; switch ( $resource ) { /* * -------------------------------------------------------------- * * options * - filter: names[], like, network(bool) * -------------------------------------------------------------- * */ case 'options': $names = isset( $filter['names'] ) && is_array( $filter['names'] ) ? array_slice( array_map( 'sanitize_key', $filter['names'] ), 0, 50 ) : array(); $like = isset( $filter['like'] ) ? sanitize_text_field( $filter['like'] ) : ''; $network = ! empty( $filter['network'] ) && is_multisite(); $rows = array(); if ( $names ) { foreach ( $names as $name ) { if ( ! $this->is_allowed_option( $name ) ) { continue; } $value = $network ? get_site_option( $name, null ) : get_option( $name, null ); $rows [] = array( 'name' => $name, 'value' => $this->sanitize_option_value( $name, $value ), ); } } elseif ( '' !== $like ) { $like_lc = strtolower( $like ); $candidate_names = self::OPTION_ALLOWLIST; if ( ! $network ) { $alloptions = wp_load_alloptions(); if ( is_array( $alloptions ) ) { foreach ( array_keys( $alloptions ) as $option_name ) { if ( ! is_string( $option_name ) || ! $this->is_allowed_option( $option_name ) ) { continue; } $candidate_names[] = $option_name; } } } $candidate_names = array_values( array_unique( $candidate_names ) ); sort( $candidate_names ); foreach ( $candidate_names as $name ) { if ( false === strpos( strtolower( $name ), $like_lc ) ) { continue; } if ( ! $this->is_allowed_option( $name ) ) { continue; } $value = $network ? get_site_option( $name, null ) : get_option( $name, null ); $rows[] = array( 'name' => $name, 'value' => $this->sanitize_option_value( $name, $value ), ); } } else { foreach ( self::OPTION_ALLOWLIST as $name ) { $value = $network ? get_site_option( $name, null ) : get_option( $name, null ); $rows [] = array( 'name' => $name, 'value' => $this->sanitize_option_value( $name, $value ), ); } } list( $page, $next ) = Pagination::paginate_array( $rows, $limit, $cursor ); $data = $page; break; /* * -------------------------------------------------------------- * * content * - type: post|term|media|menu * - subtype, ids[], slugs[], status[], search, after * -------------------------------------------------------------- * */ case 'content': $type = isset( $filter['type'] ) ? sanitize_text_field( $filter['type'] ) : 'post'; $subtype = isset( $filter['subtype'] ) ? sanitize_text_field( $filter['subtype'] ) : ''; $ids = isset( $filter['ids'] ) && is_array( $filter['ids'] ) ? array_map( 'intval', $filter['ids'] ) : array(); $slugs = isset( $filter['slugs'] ) && is_array( $filter['slugs'] ) ? array_map( 'sanitize_title', $filter['slugs'] ) : array(); $status = isset( $filter['status'] ) && is_array( $filter['status'] ) ? array_map( 'sanitize_text_field', $filter['status'] ) : array(); $search = isset( $filter['search'] ) ? sanitize_text_field( $filter['search'] ) : ''; $after = isset( $filter['after'] ) ? sanitize_text_field( $filter['after'] ) : ''; $is_targeted = ! empty( $ids ) || ! empty( $slugs ) || '' !== $search; if ( 'post' === $type || 'media' === $type ) { $pt = 'media' === $type ? 'attachment' : ( '' !== $subtype ? $subtype : 'any' ); $page_limit = $is_targeted ? $limit : min( $limit, 25 ); // Support cursor as offset. $offset = $this->decode_cursor_offset( $cursor ); $args = array( 'post_type' => $pt, 'posts_per_page' => $page_limit, 'offset' => $offset, 'orderby' => 'date', 'order' => 'DESC', 'no_found_rows' => false, 'ignore_sticky_posts' => true, ); if ( $ids ) { $args['post__in'] = $ids; } if ( $slugs ) { $args['post_name__in'] = $slugs; } $allowed_statuses = array( 'publish', 'future', 'pending', 'draft', 'private' ); if ( $status ) { $status = array_values( array_intersect( $status, $allowed_statuses ) ); } if ( ! $status ) { $status = array( 'publish' ); } $args['post_status'] = $status; if ( $search ) { $args['s'] = $search; } if ( $after ) { $args['date_query'] = array( array( 'after' => $after, 'inclusive' => true, ), ); } $q = new WP_Query( $args ); $rows = array(); if ( $q->have_posts() ) { foreach ( $q->posts as $p ) { $rows[] = array( 'id' => (int) $p->ID, 'type' => get_post_type( $p ), 'status' => $p->post_status, 'slug' => $p->post_name, 'title' => Redactor::redact( get_the_title( $p ) ), 'modified' => get_post_modified_time( 'c', true, $p ), 'url' => Redactor::redact( get_permalink( $p ) ), ); if ( $is_targeted ) { $rows[ count( $rows ) - 1 ]['excerpt'] = Redactor::redact( wp_trim_words( wp_strip_all_tags( $p->post_content ), 40, '…' ) ); } } } $found = (int) ( $q->found_posts ?? 0 ); $new_off = $offset + count( $rows ); if ( $new_off < $found ) { // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- Cursor pagination stores a compact JSON offset. $next = array( 'cursor' => base64_encode( wp_json_encode( array( 'offset' => $new_off ) ) ) ); } $data = $rows; } elseif ( 'term' === $type ) { $tax = '' !== $subtype ? $subtype : 'category'; $args = array( 'taxonomy' => $tax, 'hide_empty' => false, 'number' => $limit, 'offset' => 0, ); $args['offset'] = $this->decode_cursor_offset( $cursor ); if ( $ids ) { $args['include'] = $ids; } if ( $slugs ) { $args['slug'] = $slugs; } if ( $search ) { $args['search'] = $search; } $terms = get_terms( $args ); $rows = array(); if ( ! is_wp_error( $terms ) ) { foreach ( $terms as $t ) { $rows[] = array( 'id' => (int) $t->term_id, 'slug' => $t->slug, 'name' => Redactor::redact( $t->name ), 'count' => (int) $t->count, 'taxonomy' => $t->taxonomy, 'link' => Redactor::redact( get_term_link( $t ) ), ); } // Note: get_terms does not provide a total, so a filled page implies there may be more results. if ( count( $terms ) === $limit ) { // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- Cursor pagination stores a compact JSON offset. $next = array( 'cursor' => base64_encode( wp_json_encode( array( 'offset' => $args['offset'] + $limit ) ) ) ); } } $data = $rows; } elseif ( 'menu' === $type ) { // Return menus or their items. $menus = wp_get_nav_menus(); $rows = array(); foreach ( $menus as $m ) { $item_count = wp_get_nav_menu_items( $m->term_id, array( 'count' => true ) ); $rows[] = array( 'id' => (int) $m->term_id, 'slug' => $m->slug, 'name' => Redactor::redact( $m->name ), 'items' => false !== $item_count ? (int) $item_count : null, 'location_count' => count( array_keys( get_nav_menu_locations(), $m->term_id, true ) ), ); } list( $page, $next ) = Pagination::paginate_array( $rows, $limit, $cursor ); $data = $page; } else { $data = array(); } break; /* * -------------------------------------------------------------- * * plugins (full list + active flag + update info) * -------------------------------------------------------------- * */ case 'plugins': if ( ! function_exists( 'get_plugins' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } $all = get_plugins(); $active = (array) get_option( 'active_plugins', array() ); $updates = get_site_transient( 'update_plugins' ); $updates_map = ( $updates && is_object( $updates ) && isset( $updates->response ) && is_array( $updates->response ) ) ? $updates->response : array(); $rows = array(); foreach ( $all as $file => $plugin_meta ) { $rows[] = array( 'file' => $file, 'name' => Redactor::redact( $plugin_meta['Name'] ?? '' ), 'version' => $plugin_meta['Version'] ?? '', 'active' => in_array( $file, $active, true ), 'update' => isset( $updates_map[ $file ] ) ? array( 'available' => true, 'new_version' => $updates_map[ $file ]->new_version ?? null, ) : null, ); } list( $page, $next ) = Pagination::paginate_array( $rows, $limit, $cursor ); $data = $page; break; /* * -------------------------------------------------------------- * * theme (active + parent + counts + theme.json presence quick look) * -------------------------------------------------------------- * */ case 'theme': $theme = wp_get_theme(); $parent = $theme->parent(); $is_block = function_exists( 'wp_is_block_theme' ) ? wp_is_block_theme() : false; $data = array( 'active' => array( 'name' => $theme->get( 'Name' ), 'ver' => $theme->get( 'Version' ), ), 'parent' => $parent ? array( 'name' => $parent->get( 'Name' ), 'ver' => $parent->get( 'Version' ), ) : null, 'is_block_theme' => (bool) $is_block, 'has_theme_json' => file_exists( get_stylesheet_directory() . '/theme.json' ), ); break; /* * -------------------------------------------------------------- * * runtime (cron + rewrite rules) * - overdue(bool), hook_like(string) * -------------------------------------------------------------- * */ case 'runtime': $overdue = ! empty( $filter['overdue'] ); $hook_like = isset( $filter['hook_like'] ) ? sanitize_text_field( $filter['hook_like'] ) : ''; // Cron. $ca = _get_cron_array(); $now = time(); $cron_rows = array(); if ( is_array( $ca ) ) { foreach ( $ca as $ts => $hooks ) { foreach ( $hooks as $hook => $events ) { $due_in = (int) $ts - $now; $schedule = null; foreach ( $events as $evt ) { $schedule = $evt['schedule'] ?? null; break; } if ( $overdue && $due_in >= 0 ) { continue; } if ( $hook_like && stripos( $hook, $hook_like ) === false ) { continue; } $cron_rows[] = array( 'hook' => $hook, 'ts' => (int) $ts, 'ts_iso' => $this->timestamp_to_iso( (int) $ts ), 'due_in_s' => $due_in, 'schedule' => $schedule, ); } } // Show soonest first. usort( $cron_rows, fn( $a, $b )=> $a['ts'] <=> $b['ts'] ); } list( $cron_page, $cron_next ) = Pagination::paginate_array( $cron_rows, $limit, $cursor ); // Rewrite rules. $rewrite_rules = get_option( 'rewrite_rules' ); if ( ! is_array( $rewrite_rules ) ) { $rewrite_rules = array(); } $data = array( 'cron' => $cron_page, 'rewrite_rules_count' => is_array( $rewrite_rules ) ? count( $rewrite_rules ) : 0, ); if ( $cron_next ) { $next = $cron_next; } break; /* * -------------------------------------------------------------- * * site_health (WordPress Site Health report) * -------------------------------------------------------------- * */ case 'site_health': if ( ! class_exists( 'WP_Site_Health' ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php'; } $this->ensure_site_health_dependencies_loaded(); $health = WP_Site_Health::get_instance(); $tests = $health->get_tests(); $results = array(); $counts = array( 'good' => 0, 'recommended' => 0, 'critical' => 0, ); foreach ( array( 'direct', 'async' ) as $group ) { foreach ( (array) ( $tests[ $group ] ?? array() ) as $test_id => $test ) { if ( ! is_array( $test ) || empty( $test['test'] ) ) { continue; } $test_callback = $test['test']; if ( 'async' === $group && ! empty( $test['async_direct_test'] ) ) { $test_callback = $test['async_direct_test']; } try { $result = $this->run_site_health_test( $health, $test_callback, (string) $test_id ); } catch ( \Throwable $e ) { $error_message = Redactor::redact( $e->getMessage() ); $is_missing_function = str_contains( $e->getMessage(), 'Call to undefined function' ); $result = array( 'status' => $is_missing_function ? 'recommended' : 'critical', 'label' => $test['label'] ?? (string) $test_id, 'description' => sprintf( $is_missing_function ? 'Site health test could not run in this request context: %s' : 'Site health test failed to run: %s', $error_message ), ); } if ( ! is_array( $result ) ) { continue; } $status = $result['status'] ?? 'good'; if ( isset( $counts[ $status ] ) ) { ++$counts[ $status ]; } $row = array( 'id' => (string) $test_id, 'label' => Redactor::redact( $result['label'] ?? ( $test['label'] ?? $test_id ) ), 'status' => $status, 'badge' => isset( $result['badge']['label'] ) ? Redactor::redact( $result['badge']['label'] ) : null, ); $description = isset( $result['description'] ) ? (string) $result['description'] : ''; if ( '' !== $description && 'good' !== $status ) { $row['reason'] = Redactor::redact_readable_diagnostic( $this->trim_site_health_reason( $description ) ); } $results[] = $row; } } usort( $results, static function ( array $a, array $b ): int { $weights = array( 'critical' => 0, 'recommended' => 1, 'good' => 2, ); $a_weight = $weights[ $a['status'] ?? 'good' ] ?? 3; $b_weight = $weights[ $b['status'] ?? 'good' ] ?? 3; if ( $a_weight !== $b_weight ) { return $a_weight <=> $b_weight; } return strcmp( (string) ( $a['label'] ?? '' ), (string) ( $b['label'] ?? '' ) ); } ); $overall = 'good'; if ( $counts['critical'] > 0 ) { $overall = 'critical'; } elseif ( $counts['recommended'] > 0 ) { $overall = 'recommended'; } $data = array( 'summary' => array( 'overall' => $overall, 'counts' => $counts, 'summary_note' => 'Full Site Health test output. This can differ from the lightweight site_context health snapshot.', ), 'tests' => array_slice( $results, 0, min( $limit, 50 ) ), ); break; /* * -------------------------------------------------------------- * * rest (routes with filtering) * - like (substring on route), methods[] * -------------------------------------------------------------- * */ case 'rest': $like = isset( $filter['like'] ) ? sanitize_text_field( $filter['like'] ) : ''; $methods = isset( $filter['methods'] ) && is_array( $filter['methods'] ) ? array_map( 'strtoupper', $filter['methods'] ) : array(); $routes = function_exists( 'rest_get_server' ) ? rest_get_server()->get_routes() : array(); $flat = RestRoutes::flatten( $routes ); $meta['summary'] = Diagnostics::summarize_rest_routes( array_map( static fn( array $route ): string => (string) ( $route['route'] ?? '' ), $flat ), 10, 12, 'flattened_non_sensitive_routes' ); $meta['summary']['summary_note'] = 'This summary is based on flattened non-sensitive routes. Site context uses raw registered routes, so counts may differ.'; // Apply optional route filters. if ( '' !== $like ) { $flat = array_values( array_filter( $flat, static fn( array $route ): bool => false !== stripos( $route['route'], $like ) ) ); } if ( $methods ) { $flat = array_values( array_filter( $flat, function ( $r ) use ( $methods ) { return count( array_intersect( $r['methods'], $methods ) ) > 0; } ) ); } $page_limit = ( '' === $like && empty( $methods ) ) ? min( $limit, 25 ) : $limit; list($page, $next) = Pagination::paginate_array( $flat, $page_limit, $cursor ); $data = $page; break; /* * -------------------------------------------------------------- * * hooks (top callbacks per hook, anonymized) * -------------------------------------------------------------- * */ case 'hooks': global $wp_filter; $rows = array(); $total_callbacks = 0; foreach ( (array) $wp_filter as $hook => $hook_obj ) { if ( ! $hook_obj instanceof WP_Hook ) { continue; } $count = 0; if ( is_array( $hook_obj->callbacks ) ) { foreach ( $hook_obj->callbacks as $priority => $callbacks ) { foreach ( (array) $callbacks as $cb ) { ++$count; } } } $total_callbacks += $count; $rows[] = array( 'hook' => (string) $hook, 'callbacks' => $count, ); } usort( $rows, static fn( $a, $b ) => $b['callbacks'] <=> $a['callbacks'] ); $meta['summary'] = array( 'total_hooks' => count( $rows ), 'total_callbacks' => $total_callbacks, ); list( $page, $next ) = Pagination::paginate_array( $rows, min( $limit, 25 ), $cursor ); $data = $page; break; /* * -------------------------------------------------------------- * * performance * - autoload_top (int) * - url (string) => basic enqueue extraction (from HTML) + cache hints * -------------------------------------------------------------- * */ case 'performance': $autoload_top = isset( $filter['autoload_top'] ) ? max( 1, (int) $filter['autoload_top'] ) : 0; $url = isset( $filter['url'] ) ? esc_url_raw( $filter['url'] ) : ''; $result = array(); if ( $autoload_top <= 0 && '' === $url ) { $meta['hint'] = 'Provide filter.autoload_top or filter.url for performance analysis.'; } if ( $autoload_top > 0 ) { $alloptions = wp_load_alloptions(); $rows = array(); $sum = 0; if ( is_array( $alloptions ) ) { foreach ( $alloptions as $option_name => $option_value ) { $bytes = strlen( maybe_serialize( $option_value ) ); $rows[] = array( 'option_name' => (string) $option_name, 'bytes' => $bytes, ); $sum += $bytes; } usort( $rows, static fn( array $a, array $b ): int => (int) $b['bytes'] <=> (int) $a['bytes'] ); $rows = array_slice( $rows, 0, $autoload_top ); } $out = array(); foreach ( (array) $rows as $r ) { $row_kb = (int) round( $r['bytes'] / 1024 ); if ( $row_kb <= 0 ) { continue; } $out[] = array( 'name' => Redactor::redact( $r['option_name'] ), 'kb' => $row_kb, ); } $result['autoload'] = array( 'total_kb' => (int) round( $sum / 1024 ), 'top' => $out, ); } if ( $url ) { if ( str_starts_with( $url, '/' ) ) { $url = home_url( $url ); } $parts = wp_parse_url( $url ); $allowed = array(); $home_host = wp_parse_url( home_url(), PHP_URL_HOST ); if ( $home_host ) { $allowed[] = strtolower( (string) $home_host ); } $site_host = wp_parse_url( site_url(), PHP_URL_HOST ); if ( $site_host ) { $allowed[] = strtolower( (string) $site_host ); } $target_host = strtolower( $parts['host'] ?? '' ); if ( ! $parts || ! in_array( $target_host, array_unique( $allowed ), true ) ) { $data = $result; break; } $resp = Http::fetch( $url, 'GET', array(), 20 ); $html = is_array( $resp ) ? ( $resp['body'] ?? '' ) : ''; $assets = Html::collect_enqueues( $html, $url ); $result['enqueues'] = $assets; if ( is_array( $resp ) ) { $result['http'] = array( 'check_type' => 'full_page_fetch_and_asset_scan', 'method' => 'GET', 'code' => $resp['code'] ?? null, 'headers' => $this->filter_http_headers( Http::headers_to_array( $resp['headers'] ?? array() ) ), 'obs' => $resp['observations'] ?? array(), 'content_type' => $resp['content_type'] ?? null, 'bytes' => isset( $resp['body_bytes'] ) ? (int) $resp['body_bytes'] : null, 'error' => $resp['error'] ?? null, 'error_code' => $resp['error_code'] ?? null, 'error_message' => $resp['message'] ?? null, 'attempts' => isset( $resp['attempts'] ) ? (int) $resp['attempts'] : 1, 'retry_count' => isset( $resp['attempts'] ) ? max( 0, (int) $resp['attempts'] - 1 ) : 0, 'timeout_s' => isset( $resp['timeout_s'] ) ? (int) $resp['timeout_s'] : 20, ); if ( ! empty( $resp['error'] ) ) { $result['http']['message'] = 'Full page fetch and asset scan failed.'; } } } $data = $result; break; /* * -------------------------------------------------------------- * * http * - url, method(GET|HEAD|POST), headers{}, timeout_s * -------------------------------------------------------------- * */ case 'http': $start = microtime( true ); $url = isset( $filter['url'] ) && is_string( $filter['url'] ) ? trim( $filter['url'] ) : ''; $method = isset( $filter['method'] ) && is_string( $filter['method'] ) ? strtoupper( $filter['method'] ) : 'GET'; $timeout = isset( $filter['timeout_s'] ) ? max( 1, (int) $filter['timeout_s'] ) : 15; $hdrs = Http::sanitize_headers( $filter['headers'] ?? array() ); if ( ! $url ) { return new WP_REST_Response( array( 'error' => 'bad_request', 'message' => 'Missing url', ), 400 ); } if ( str_starts_with( $url, '/' ) ) { $url = home_url( $url ); } if ( ! in_array( $method, array( 'GET', 'HEAD', 'POST' ), true ) ) { return new WP_REST_Response( array( 'error' => 'bad_request', 'message' => 'Unsupported method', ), 400 ); } $parsed = wp_parse_url( $url ); if ( ! $parsed || empty( $parsed['scheme'] ) || empty( $parsed['host'] ) ) { return new WP_REST_Response( array( 'error' => 'bad_request', 'message' => 'Invalid url', ), 400 ); } if ( ! in_array( strtolower( $parsed['scheme'] ), array( 'http', 'https' ), true ) ) { return new WP_REST_Response( array( 'error' => 'bad_request', 'message' => 'Unsupported scheme', ), 400 ); } $site_hosts = array(); $home_host = wp_parse_url( home_url(), PHP_URL_HOST ); if ( $home_host ) { $site_hosts[] = strtolower( (string) $home_host ); } $site_host = wp_parse_url( site_url(), PHP_URL_HOST ); if ( $site_host ) { $site_hosts[] = strtolower( (string) $site_host ); } $allowed_hosts = array_unique( array_filter( $site_hosts ) ); $target_host = strtolower( $parsed['host'] ); if ( ! in_array( $target_host, $allowed_hosts, true ) ) { return new WP_REST_Response( array( 'error' => 'forbidden', 'message' => 'HTTP fetch is limited to this WordPress site.', ), 403 ); } // Default the user agent if the caller did not provide one. if ( ! isset( $hdrs['User-Agent'] ) ) { $hdrs['User-Agent'] = 'ActionPanel-AI/' . ACTIONPANEL_AI_PLUGIN_VERSION . ' WP/' . get_bloginfo( 'version' ); } // NOTE: This endpoint intentionally does not accept arbitrary POST bodies. // If the schema changes later, keep strict size and content-type limits. $resp = Http::fetch( $url, $method, $hdrs, $timeout ); if ( isset( $resp['error'] ) ) { return new WP_REST_Response( array( 'meta' => array( 'resource' => 'http', 'generated_at' => time(), 'duration_ms' => (int) ( ( microtime( true ) - $start ) * 1000 ), 'url' => $url, ), 'data' => array(), 'error' => array( 'type' => 'wp_error', 'code' => $resp['error_code'] ?? 'request_failed', 'message' => $resp['message'] ?? 'Request failed', 'codes' => $resp['error_codes'] ?? array(), 'attempts' => isset( $resp['attempts'] ) ? (int) $resp['attempts'] : 1, 'timeout_s' => isset( $resp['timeout_s'] ) ? (int) $resp['timeout_s'] : $timeout, ), ), 200 ); } $status_code = (int) ( $resp['code'] ?? 0 ); $status_msg = (string) ( $resp['status_text'] ?? '' ); $headers = $this->filter_http_headers( Http::headers_to_array( $resp['headers'] ?? array() ) ); $body = (string) ( $resp['body'] ?? '' ); $original_len = strlen( $body ); $content_type = isset( $resp['content_type'] ) && is_string( $resp['content_type'] ) ? $resp['content_type'] : ( isset( $headers['content-type'] ) ? ( is_array( $headers['content-type'] ) ? implode( ', ', $headers['content-type'] ) : (string) $headers['content-type'] ) : '' ); $body_summary = $this->summarize_http_body( $body, $content_type ); return new WP_REST_Response( array( 'meta' => array( 'resource' => 'http', 'generated_at' => time(), 'duration_ms' => (int) ( ( microtime( true ) - $start ) * 1000 ), 'url' => $url, 'attempts' => isset( $resp['attempts'] ) ? (int) $resp['attempts'] : 1, ), 'data' => array( array( 'status' => $status_code, 'status_text' => $status_msg, 'headers' => $headers, 'observations' => $resp['observations'] ?? array(), 'content_type' => $content_type, 'body_bytes' => $original_len, 'truncated' => (bool) ( $body_summary['truncated'] ?? false ), 'body_kind' => $body_summary['body_kind'] ?? 'unknown', 'body_preview' => $body_summary['body_preview'] ?? '', 'body_summary' => $body_summary['body_summary'] ?? null, ), ), ), 200 ); /* * -------------------------------------------------------------- * * commerce (WooCommerce summary) * -------------------------------------------------------------- * */ case 'commerce': $out = array( 'active' => false ); if ( class_exists( 'WooCommerce' ) ) { $out['active'] = true; $out['version'] = defined( 'WC_VERSION' ) ? WC_VERSION : null; // Pages status. $pages = array( 'shop' => wc_get_page_id( 'shop' ), 'cart' => wc_get_page_id( 'cart' ), 'checkout' => wc_get_page_id( 'checkout' ), 'myaccount' => wc_get_page_id( 'myaccount' ), ); $out['pages'] = array_map( 'intval', $pages ); // Gateways enabled. if ( function_exists( 'WC' ) && WC()->payment_gateways() ) { $gws = WC()->payment_gateways()->get_available_payment_gateways(); $out['gateways_enabled'] = array_values( array_map( static fn( $gateway ) => $gateway->id, is_array( $gws ) ? $gws : array() ) ); } // Shipping zones. if ( class_exists( 'WC_Shipping_Zones' ) ) { $zones = \WC_Shipping_Zones::get_zones(); $out['shipping_zones'] = is_array( $zones ) ? count( $zones ) : 0; } // Template overrides. $out['template_overrides'] = WooCommerce::overrides_list(); } $data = $out; break; /* * -------------------------------------------------------------- * * logs (tail from end) * - use limit as number of lines (default 50) * -------------------------------------------------------------- * */ case 'logs': if ( ! $this->settings->is_log_reads_active() ) { return new WP_REST_Response( array( 'error' => 'logs_disabled', 'message' => 'Debug log reads are disabled in ActionPanel AI settings.', ), 403 ); } $lines = $limit > 0 ? $limit : 50; $lines = max( 10, min( 200, $lines ) ); $backend = $this->settings->get_log_reads_backend(); $log_path = $this->settings->get_log_reads_path(); if ( $log_path && file_exists( $log_path ) && is_readable( $log_path ) ) { $tail = Filesystem::tail_lines( $log_path, $lines, self::LOG_MAX_BYTES ); $sanitized_lines = array(); if ( '' !== $tail ) { foreach ( explode( "\n", $tail ) as $line ) { $line = trim( $line ); if ( '' === $line ) { continue; } $sanitized_lines[] = $this->sanitize_log_text( $line ); } } $sanitized_lines = $this->dedupe_log_lines( $sanitized_lines ); $data = array( 'status' => 'ok', 'backend' => '' !== $backend ? $backend : 'unknown', 'lines' => $sanitized_lines, ); if ( count( $sanitized_lines ) <= 1 ) { $meta['note'] = 'No recent diagnostic events found in the configured WordPress debug log.'; } } else { $data = array( 'status' => 'unavailable', 'backend' => '' !== $backend ? $backend : 'unknown', 'reason' => ! $log_path ? 'not_configured' : ( file_exists( $log_path ) ? 'not_readable' : 'not_created' ), ); } break; /* * -------------------------------------------------------------- * * users (aggregated, masked) * -------------------------------------------------------------- * */ case 'users': $counts = count_users(); $roles = array(); if ( isset( $counts['avail_roles'] ) && is_array( $counts['avail_roles'] ) ) { foreach ( $counts['avail_roles'] as $role_name => $count ) { $roles[] = array( 'role' => (string) $role_name, 'count' => (int) $count, ); } } $sample_limit = max( 1, min( 5, $limit ) ); $sample_users = get_users( array( 'number' => $sample_limit, 'orderby' => 'registered', 'order' => 'DESC', 'fields' => array( 'ID', 'user_email', 'user_login', 'display_name', 'user_registered', 'roles' ), ) ); $sample = array(); foreach ( (array) $sample_users as $user ) { $user_id = isset( $user->ID ) ? (int) $user->ID : 0; $resolved_roles = array(); if ( $user instanceof \WP_User ) { $resolved_roles = array_values( (array) $user->roles ); } elseif ( isset( $user->roles ) ) { $resolved_roles = array_values( (array) $user->roles ); } elseif ( $user_id > 0 ) { $wp_user = get_userdata( $user_id ); if ( $wp_user instanceof \WP_User ) { $resolved_roles = array_values( (array) $wp_user->roles ); } } $display_name = isset( $user->display_name ) ? (string) $user->display_name : ''; $user_registered = isset( $user->user_registered ) ? (string) $user->user_registered : ''; $user_email = isset( $user->user_email ) ? (string) $user->user_email : ''; $user_login = isset( $user->user_login ) ? (string) $user->user_login : ''; $sample[] = array( 'id' => $user_id, 'display' => Redactor::redact( $display_name ), 'roles' => $resolved_roles, 'registered' => $user_registered, 'email' => Strings::mask_email( $user_email ), 'login_hash' => '' !== $user_login ? substr( sha1( $user_login ), 0, 10 ) : '', ); } $data = array( 'total_users' => (int) ( $counts['total_users'] ?? 0 ), 'roles' => $roles, 'sample' => $sample, ); break; /* * -------------------------------------------------------------- * * template (resolve for url or post_id) * - url or post_id * -------------------------------------------------------------- * */ case 'template': $url = isset( $filter['url'] ) ? esc_url_raw( $filter['url'] ) : ''; $post_id = isset( $filter['post_id'] ) ? (int) $filter['post_id'] : 0; if ( ! $url && ! $post_id ) { $meta['hint'] = 'Provide filter.url or filter.post_id to resolve a template.'; } $data = TemplateResolver::resolve( $url, $post_id ); if ( is_array( $data ) && isset( $data['selected'] ) && empty( $data['candidates'] ) && ! isset( $data['candidate_trace_available'] ) ) { $data['candidate_trace_available'] = false; $data['candidate_trace_reason'] = 'candidate derivation unavailable'; } break; /* * -------------------------------------------------------------- * * server (sanitized server config snippets) * -------------------------------------------------------------- * */ case 'server': if ( ! function_exists( 'get_home_path' ) ) { require_once ABSPATH . 'wp-admin/includes/file.php'; } if ( ! function_exists( 'get_dropins' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } /* * Read-only server diagnostics are limited to short sanitized snippets * from common home-root config files discovered through WordPress * helpers. This does not create, manage, or relocate server files. */ $home_path = function_exists( 'get_home_path' ) ? get_home_path() : ''; $rows = array(); foreach ( array( '.htaccess', 'web.config', 'nginx.conf' ) as $basename ) { if ( '' === $home_path ) { continue; } $file = trailingslashit( $home_path ) . $basename; if ( ! file_exists( $file ) || ! is_readable( $file ) ) { continue; } // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Reads home-root config snippets discovered via get_home_path(). $contents = file_get_contents( $file ); if ( false === $contents ) { continue; } $rows[] = array( 'file' => $basename, 'bytes' => filesize( $file ), 'mtime' => filemtime( $file ), 'mtime_iso' => $this->timestamp_to_iso( (int) filemtime( $file ) ), 'snippet' => Redactor::redact( substr( $contents, 0, 1200 ) ), ); } $dropins = function_exists( 'get_dropins' ) ? get_dropins() : array(); if ( isset( $dropins['advanced-cache.php'] ) && is_array( $dropins['advanced-cache.php'] ) ) { $rows[] = array( 'file' => 'advanced-cache.php', 'type' => 'dropin', 'name' => $dropins['advanced-cache.php']['Name'] ?? 'advanced-cache.php', 'author' => isset( $dropins['advanced-cache.php']['AuthorName'] ) ? Redactor::redact( (string) $dropins['advanced-cache.php']['AuthorName'] ) : '', 'description' => isset( $dropins['advanced-cache.php']['Description'] ) ? Redactor::redact( (string) $dropins['advanced-cache.php']['Description'] ) : '', ); } $rows = array_values( array_filter( $rows, static fn( array $row ): bool => ! empty( $row['snippet'] ) || 'dropin' === ( $row['type'] ?? '' ) ) ); $data = $rows; break; /* * -------------------------------------------------------------- * * files (scope-specific metadata / text) * - scope, target, relative_path * -------------------------------------------------------------- * */ case 'files': $resolved = Filesystem::resolve_read_request( is_array( $filter ) ? $filter : array() ); if ( ! $resolved['allowed'] ) { $reason = (string) ( $resolved['reason'] ?? 'policy_violation' ); $status = in_array( $reason, array( 'missing_scope', 'invalid_scope', 'missing_target', 'missing_relative_path' ), true ) ? 400 : 403; return new WP_REST_Response( array( 'error' => 'path_not_allowed', 'message' => $this->files_path_error_message( $reason ), 'reason' => $reason, ), $status ); } if ( 'file' === ( $resolved['kind'] ?? '' ) && ! empty( $resolved['real'] ) && ! empty( $resolved['display_path'] ) && ! empty( $resolved['scope'] ) ) { $data = Filesystem::describe_local_file( (string) $resolved['display_path'], (string) $resolved['real'], (string) $resolved['scope'] ); break; } if ( 'manifest' === ( $resolved['kind'] ?? '' ) ) { $data = array( 'scope' => $resolved['scope'] ?? 'plugin_manifest', 'metadata' => $resolved['metadata'] ?? array(), 'files' => $resolved['files'] ?? array(), 'count' => is_array( $resolved['files'] ?? null ) ? count( $resolved['files'] ) : 0, ); break; } if ( 'metadata' === ( $resolved['kind'] ?? '' ) ) { $data = array( 'scope' => $resolved['scope'] ?? 'metadata', 'metadata' => $resolved['metadata'] ?? array(), ); break; } return new WP_REST_Response( array( 'error' => 'unsupported_files_resolution', 'message' => 'The requested files scope did not resolve to a supported response.', ), 500 ); /* * -------------------------------------------------------------- * * transients/cache metadata * -------------------------------------------------------------- * */ case 'transients': $limit = max( 1, min( 100, $limit ) ); $data = $this->load_transient_metadata( $limit, $meta ); $meta['zero_size_rows_filtered'] = true; break; default: return new WP_REST_Response( array( 'error' => 'unsupported_resource', 'message' => 'The requested read-site resource is not supported.', 'resource' => $resource, ), 400 ); } $generated_at = time(); $meta = array_merge( $meta, array( 'resource' => $resource, 'generated_at' => $generated_at, 'generated_at_iso' => $this->timestamp_to_iso( $generated_at ), 'duration_ms' => (int) round( ( microtime( true ) - $__t0 ) * 1000 ), ) ); $payload = array( 'meta' => $meta, 'data' => $data, ); if ( isset( $meta['hint'] ) && is_string( $meta['hint'] ) && '' !== $meta['hint'] ) { $payload['hint'] = $meta['hint']; } if ( isset( $meta['note'] ) && is_string( $meta['note'] ) && '' !== $meta['note'] ) { $payload['note'] = $meta['note']; } if ( $next ) { $payload['next'] = $next; } return new WP_REST_Response( $payload ); } catch ( Throwable $e ) { return new WP_REST_Response( array( 'error' => 'server_error', 'exception' => get_class( $e ), ), 500 ); } } }