[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-admin/includes/ -> class-wp-site-health.php (source)

   1  <?php
   2  /**
   3   * Class for looking up a site's health based on a user's WordPress environment.
   4   *
   5   * @package WordPress
   6   * @subpackage Site_Health
   7   * @since 5.2.0
   8   */
   9  
  10  #[AllowDynamicProperties]
  11  class WP_Site_Health {
  12      private static $instance = null;
  13  
  14      private $is_acceptable_mysql_version;
  15      private $is_recommended_mysql_version;
  16  
  17      public $is_mariadb                   = false;
  18      private $mysql_server_version        = '';
  19      private $mysql_required_version      = '5.5';
  20      private $mysql_recommended_version   = '8.4';
  21      private $mariadb_recommended_version = '10.11';
  22  
  23      public $php_memory_limit;
  24  
  25      public $schedules;
  26      public $crons;
  27      public $last_missed_cron     = null;
  28      public $last_late_cron       = null;
  29      private $timeout_missed_cron = null;
  30      private $timeout_late_cron   = null;
  31  
  32      /**
  33       * WP_Site_Health constructor.
  34       *
  35       * @since 5.2.0
  36       */
  37  	public function __construct() {
  38          $this->maybe_create_scheduled_event();
  39  
  40          // Save memory limit before it's affected by wp_raise_memory_limit( 'admin' ).
  41          $this->php_memory_limit = ini_get( 'memory_limit' );
  42  
  43          $this->timeout_late_cron   = 0;
  44          $this->timeout_missed_cron = - 5 * MINUTE_IN_SECONDS;
  45  
  46          if ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ) {
  47              $this->timeout_late_cron   = - 15 * MINUTE_IN_SECONDS;
  48              $this->timeout_missed_cron = - 1 * HOUR_IN_SECONDS;
  49          }
  50  
  51          add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
  52  
  53          add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
  54          add_action( 'wp_site_health_scheduled_check', array( $this, 'wp_cron_scheduled_check' ) );
  55  
  56          add_action( 'site_health_tab_content', array( $this, 'show_site_health_tab' ) );
  57      }
  58  
  59      /**
  60       * Outputs the content of a tab in the Site Health screen.
  61       *
  62       * @since 5.8.0
  63       *
  64       * @param string $tab Slug of the current tab being displayed.
  65       */
  66  	public function show_site_health_tab( $tab ) {
  67          if ( 'debug' === $tab ) {
  68              require_once  ABSPATH . 'wp-admin/site-health-info.php';
  69          }
  70      }
  71  
  72      /**
  73       * Returns an instance of the WP_Site_Health class, or create one if none exist yet.
  74       *
  75       * @since 5.4.0
  76       *
  77       * @return WP_Site_Health|null
  78       */
  79  	public static function get_instance() {
  80          self::$instance ??= new WP_Site_Health();
  81  
  82          return self::$instance;
  83      }
  84  
  85      /**
  86       * Enqueues the site health scripts.
  87       *
  88       * @since 5.2.0
  89       */
  90  	public function enqueue_scripts() {
  91          $screen = get_current_screen();
  92          if ( 'site-health' !== $screen->id && 'dashboard' !== $screen->id ) {
  93              return;
  94          }
  95  
  96          $health_check_js_variables = array(
  97              'screen'      => $screen->id,
  98              'nonce'       => array(
  99                  'site_status'        => wp_create_nonce( 'health-check-site-status' ),
 100                  'site_status_result' => wp_create_nonce( 'health-check-site-status-result' ),
 101              ),
 102              'site_status' => array(
 103                  'direct' => array(),
 104                  'async'  => array(),
 105                  'issues' => array(
 106                      'good'        => 0,
 107                      'recommended' => 0,
 108                      'critical'    => 0,
 109                  ),
 110              ),
 111          );
 112  
 113          $issue_counts = get_transient( 'health-check-site-status-result' );
 114  
 115          if ( false !== $issue_counts ) {
 116              $issue_counts = json_decode( $issue_counts );
 117  
 118              $health_check_js_variables['site_status']['issues'] = $issue_counts;
 119          }
 120  
 121          if ( 'site-health' === $screen->id && ( ! isset( $_GET['tab'] ) || empty( $_GET['tab'] ) ) ) {
 122              $tests = WP_Site_Health::get_tests();
 123  
 124              // Don't run https test on development environments.
 125              if ( $this->is_development_environment() ) {
 126                  unset( $tests['async']['https_status'] );
 127              }
 128  
 129              foreach ( $tests['direct'] as $test ) {
 130                  if ( is_string( $test['test'] ) ) {
 131                      $test_function = sprintf(
 132                          'get_test_%s',
 133                          $test['test']
 134                      );
 135  
 136                      if ( method_exists( $this, $test_function ) && is_callable( array( $this, $test_function ) ) ) {
 137                          $health_check_js_variables['site_status']['direct'][] = $this->perform_test( array( $this, $test_function ) );
 138                          continue;
 139                      }
 140                  }
 141  
 142                  if ( is_callable( $test['test'] ) ) {
 143                      $health_check_js_variables['site_status']['direct'][] = $this->perform_test( $test['test'] );
 144                  }
 145              }
 146  
 147              foreach ( $tests['async'] as $test ) {
 148                  if ( is_string( $test['test'] ) ) {
 149                      $health_check_js_variables['site_status']['async'][] = array(
 150                          'test'      => $test['test'],
 151                          'has_rest'  => $test['has_rest'] ?? false,
 152                          'completed' => false,
 153                          'headers'   => $test['headers'] ?? array(),
 154                      );
 155                  }
 156              }
 157          }
 158  
 159          wp_localize_script( 'site-health', 'SiteHealth', $health_check_js_variables );
 160      }
 161  
 162      /**
 163       * Runs a Site Health test directly.
 164       *
 165       * @since 5.4.0
 166       *
 167       * @param callable $callback
 168       * @return array{
 169       *     label: string,
 170       *     status: 'good'|'recommended'|'critical',
 171       *     badge: array{
 172       *         label: string,
 173       *         color: string,
 174       *     },
 175       *     description: string,
 176       *     actions: string,
 177       *     test: string,
 178       * }
 179       */
 180  	private function perform_test( $callback ) {
 181          /**
 182           * Filters the output of a finished Site Health test.
 183           *
 184           * @since 5.3.0
 185           *
 186           * @param array $test_result {
 187           *     An associative array of test result data.
 188           *
 189           *     @type string $label       A label describing the test, and is used as a header in the output.
 190           *     @type string $status      The status of the test, which can be a value of `good`, `recommended` or `critical`.
 191           *     @type array  $badge {
 192           *         Tests are put into categories which have an associated badge shown, these can be modified and assigned here.
 193           *
 194           *         @type string $label The test label, for example `Performance`.
 195           *         @type string $color Default `blue`. A string representing a color to use for the label.
 196           *     }
 197           *     @type string $description A more descriptive explanation of what the test looks for, and why it is important for the end user.
 198           *     @type string $actions     An action to direct the user to where they can resolve the issue, if one exists.
 199           *     @type string $test        The name of the test being ran, used as a reference point.
 200           * }
 201           */
 202          return apply_filters( 'site_status_test_result', call_user_func( $callback ) );
 203      }
 204  
 205      /**
 206       * Runs the SQL version checks.
 207       *
 208       * These values are used in later tests, but the part of preparing them is more easily managed
 209       * early in the class for ease of access and discovery.
 210       *
 211       * @since 5.2.0
 212       *
 213       * @global wpdb $wpdb WordPress database abstraction object.
 214       */
 215  	private function prepare_sql_data() {
 216          global $wpdb;
 217  
 218          $mysql_server_type = $wpdb->db_server_info();
 219  
 220          $this->mysql_server_version = $wpdb->get_var( 'SELECT VERSION()' );
 221  
 222          if ( stristr( $mysql_server_type, 'mariadb' ) ) {
 223              $this->is_mariadb                = true;
 224              $this->mysql_recommended_version = $this->mariadb_recommended_version;
 225          }
 226  
 227          $this->is_acceptable_mysql_version  = version_compare( $this->mysql_required_version, $this->mysql_server_version, '<=' );
 228          $this->is_recommended_mysql_version = version_compare( $this->mysql_recommended_version, $this->mysql_server_version, '<=' );
 229      }
 230  
 231      /**
 232       * Tests whether `wp_version_check` is blocked.
 233       *
 234       * It's possible to block updates with the `wp_version_check` filter, but this can't be checked
 235       * during an Ajax call, as the filter is never introduced then.
 236       *
 237       * This filter overrides a standard page request if it's made by an admin through the Ajax call
 238       * with the right query argument to check for this.
 239       *
 240       * @since 5.2.0
 241       */
 242  	public function check_wp_version_check_exists() {
 243          if ( ! is_admin() || ! is_user_logged_in() || ! current_user_can( 'update_core' ) || ! isset( $_GET['health-check-test-wp_version_check'] ) ) {
 244              return;
 245          }
 246  
 247          echo ( has_filter( 'wp_version_check', 'wp_version_check' ) ? 'yes' : 'no' );
 248  
 249          die();
 250      }
 251  
 252      /**
 253       * Tests for WordPress version and outputs it.
 254       *
 255       * Gives various results depending on what kind of updates are available, if any, to encourage
 256       * the user to install security updates as a priority.
 257       *
 258       * @since 5.2.0
 259       *
 260       * @return array The test result.
 261       */
 262  	public function get_test_wordpress_version() {
 263          $result = array(
 264              'label'       => '',
 265              'status'      => '',
 266              'badge'       => array(
 267                  'label' => __( 'Performance' ),
 268                  'color' => 'blue',
 269              ),
 270              'description' => '',
 271              'actions'     => '',
 272              'test'        => 'wordpress_version',
 273          );
 274  
 275          $core_current_version = wp_get_wp_version();
 276          $core_updates         = get_core_updates();
 277  
 278          if ( ! is_array( $core_updates ) ) {
 279              $result['status'] = 'recommended';
 280  
 281              $result['label'] = sprintf(
 282                  /* translators: %s: Your current version of WordPress. */
 283                  __( 'WordPress version %s' ),
 284                  $core_current_version
 285              );
 286  
 287              $result['description'] = sprintf(
 288                  '<p>%s</p>',
 289                  __( 'Unable to check if any new versions of WordPress are available.' )
 290              );
 291  
 292              $result['actions'] = sprintf(
 293                  '<a href="%s">%s</a>',
 294                  esc_url( admin_url( 'update-core.php?force-check=1' ) ),
 295                  __( 'Check for updates manually' )
 296              );
 297          } else {
 298              foreach ( $core_updates as $core => $update ) {
 299                  if ( 'upgrade' === $update->response ) {
 300                      $current_version = explode( '.', $core_current_version );
 301                      $new_version     = explode( '.', $update->version );
 302  
 303                      $current_major = $current_version[0] . '.' . $current_version[1];
 304                      $new_major     = $new_version[0] . '.' . $new_version[1];
 305  
 306                      $result['label'] = sprintf(
 307                          /* translators: %s: The latest version of WordPress available. */
 308                          __( 'WordPress update available (%s)' ),
 309                          $update->version
 310                      );
 311  
 312                      $result['actions'] = sprintf(
 313                          '<a href="%s">%s</a>',
 314                          esc_url( admin_url( 'update-core.php' ) ),
 315                          __( 'Install the latest version of WordPress' )
 316                      );
 317  
 318                      if ( $current_major !== $new_major ) {
 319                          // This is a major version mismatch.
 320                          $result['status']      = 'recommended';
 321                          $result['description'] = sprintf(
 322                              '<p>%s</p>',
 323                              __( 'A new version of WordPress is available.' )
 324                          );
 325                      } else {
 326                          // This is a minor version, sometimes considered more critical.
 327                          $result['status']         = 'critical';
 328                          $result['badge']['label'] = __( 'Security' );
 329                          $result['description']    = sprintf(
 330                              '<p>%s</p>',
 331                              __( 'A new minor update is available for your site. Because minor updates often address security, it&#8217;s important to install them.' )
 332                          );
 333                      }
 334                  } else {
 335                      $result['status'] = 'good';
 336                      $result['label']  = sprintf(
 337                          /* translators: %s: The current version of WordPress installed on this site. */
 338                          __( 'Your version of WordPress (%s) is up to date' ),
 339                          $core_current_version
 340                      );
 341  
 342                      $result['description'] = sprintf(
 343                          '<p>%s</p>',
 344                          __( 'You are currently running the latest version of WordPress available, keep it up!' )
 345                      );
 346                  }
 347              }
 348          }
 349  
 350          return $result;
 351      }
 352  
 353      /**
 354       * Tests if plugins are outdated, or unnecessary.
 355       *
 356       * The test checks if your plugins are up to date, and encourages you to remove any
 357       * that are not in use.
 358       *
 359       * @since 5.2.0
 360       *
 361       * @return array The test result.
 362       */
 363  	public function get_test_plugin_version() {
 364          $result = array(
 365              'label'       => __( 'Your plugins are all up to date' ),
 366              'status'      => 'good',
 367              'badge'       => array(
 368                  'label' => __( 'Security' ),
 369                  'color' => 'blue',
 370              ),
 371              'description' => sprintf(
 372                  '<p>%s</p>',
 373                  __( 'Plugins extend your site&#8217;s functionality with things like contact forms, ecommerce and much more. That means they have deep access to your site, so it&#8217;s vital to keep them up to date.' )
 374              ),
 375              'actions'     => sprintf(
 376                  '<p><a href="%s">%s</a></p>',
 377                  esc_url( admin_url( 'plugins.php' ) ),
 378                  __( 'Manage your plugins' )
 379              ),
 380              'test'        => 'plugin_version',
 381          );
 382  
 383          $plugins        = get_plugins();
 384          $plugin_updates = get_plugin_updates();
 385  
 386          $plugins_active      = 0;
 387          $plugins_total       = 0;
 388          $plugins_need_update = 0;
 389  
 390          // Loop over the available plugins and check their versions and active state.
 391          foreach ( $plugins as $plugin_path => $plugin ) {
 392              ++$plugins_total;
 393  
 394              if ( is_plugin_active( $plugin_path ) ) {
 395                  ++$plugins_active;
 396              }
 397  
 398              if ( array_key_exists( $plugin_path, $plugin_updates ) ) {
 399                  ++$plugins_need_update;
 400              }
 401          }
 402  
 403          // Add a notice if there are outdated plugins.
 404          if ( $plugins_need_update > 0 ) {
 405              $result['status'] = 'critical';
 406  
 407              $result['label'] = __( 'You have plugins waiting to be updated' );
 408  
 409              $result['description'] .= sprintf(
 410                  '<p>%s</p>',
 411                  sprintf(
 412                      /* translators: %d: The number of outdated plugins. */
 413                      _n(
 414                          'Your site has %d plugin waiting to be updated.',
 415                          'Your site has %d plugins waiting to be updated.',
 416                          $plugins_need_update
 417                      ),
 418                      $plugins_need_update
 419                  )
 420              );
 421  
 422              $result['actions'] .= sprintf(
 423                  '<p><a href="%s">%s</a></p>',
 424                  esc_url( network_admin_url( 'plugins.php?plugin_status=upgrade' ) ),
 425                  __( 'Update your plugins' )
 426              );
 427          } else {
 428              if ( 1 === $plugins_active ) {
 429                  $result['description'] .= sprintf(
 430                      '<p>%s</p>',
 431                      __( 'Your site has 1 active plugin, and it is up to date.' )
 432                  );
 433              } elseif ( $plugins_active > 0 ) {
 434                  $result['description'] .= sprintf(
 435                      '<p>%s</p>',
 436                      sprintf(
 437                          /* translators: %d: The number of active plugins. */
 438                          _n(
 439                              'Your site has %d active plugin, and it is up to date.',
 440                              'Your site has %d active plugins, and they are all up to date.',
 441                              $plugins_active
 442                          ),
 443                          $plugins_active
 444                      )
 445                  );
 446              } else {
 447                  $result['description'] .= sprintf(
 448                      '<p>%s</p>',
 449                      __( 'Your site does not have any active plugins.' )
 450                  );
 451              }
 452          }
 453  
 454          // Check if there are inactive plugins.
 455          if ( $plugins_total > $plugins_active && ! is_multisite() ) {
 456              $unused_plugins = $plugins_total - $plugins_active;
 457  
 458              $result['status'] = 'recommended';
 459  
 460              $result['label'] = __( 'You should remove inactive plugins' );
 461  
 462              $result['description'] .= sprintf(
 463                  '<p>%s %s</p>',
 464                  sprintf(
 465                      /* translators: %d: The number of inactive plugins. */
 466                      _n(
 467                          'Your site has %d inactive plugin.',
 468                          'Your site has %d inactive plugins.',
 469                          $unused_plugins
 470                      ),
 471                      $unused_plugins
 472                  ),
 473                  __( 'Inactive plugins are tempting targets for attackers. If you are not going to use a plugin, you should consider removing it.' )
 474              );
 475  
 476              $result['actions'] .= sprintf(
 477                  '<p><a href="%s">%s</a></p>',
 478                  esc_url( admin_url( 'plugins.php?plugin_status=inactive' ) ),
 479                  __( 'Manage inactive plugins' )
 480              );
 481          }
 482  
 483          return $result;
 484      }
 485  
 486      /**
 487       * Tests if themes are outdated, or unnecessary.
 488       *
 489       * Checks if your site has a default theme (to fall back on if there is a need),
 490       * if your themes are up to date and, finally, encourages you to remove any themes
 491       * that are not needed.
 492       *
 493       * @since 5.2.0
 494       *
 495       * @return array The test results.
 496       */
 497  	public function get_test_theme_version() {
 498          $result = array(
 499              'label'       => __( 'Your themes are all up to date' ),
 500              'status'      => 'good',
 501              'badge'       => array(
 502                  'label' => __( 'Security' ),
 503                  'color' => 'blue',
 504              ),
 505              'description' => sprintf(
 506                  '<p>%s</p>',
 507                  __( 'Themes add your site&#8217;s look and feel. It&#8217;s important to keep them up to date, to stay consistent with your brand and keep your site secure.' )
 508              ),
 509              'actions'     => sprintf(
 510                  '<p><a href="%s">%s</a></p>',
 511                  esc_url( admin_url( 'themes.php' ) ),
 512                  __( 'Manage your themes' )
 513              ),
 514              'test'        => 'theme_version',
 515          );
 516  
 517          $theme_updates = get_theme_updates();
 518  
 519          $themes_total        = 0;
 520          $themes_need_updates = 0;
 521          $themes_inactive     = 0;
 522  
 523          // This value is changed during processing to determine how many themes are considered a reasonable amount.
 524          $allowed_theme_count = 1;
 525  
 526          $has_default_theme   = false;
 527          $has_unused_themes   = false;
 528          $using_default_theme = false;
 529  
 530          // Populate a list of all themes available in the install.
 531          $all_themes   = wp_get_themes();
 532          $active_theme = wp_get_theme();
 533  
 534          // If WP_DEFAULT_THEME doesn't exist, fall back to the latest core default theme.
 535          $default_theme = wp_get_theme( WP_DEFAULT_THEME );
 536          if ( ! $default_theme->exists() ) {
 537              $default_theme = WP_Theme::get_core_default_theme();
 538          }
 539  
 540          if ( $default_theme ) {
 541              $has_default_theme = true;
 542  
 543              if (
 544                  $active_theme->get_stylesheet() === $default_theme->get_stylesheet()
 545              ||
 546                  is_child_theme() && $active_theme->get_template() === $default_theme->get_template()
 547              ) {
 548                  $using_default_theme = true;
 549              }
 550          }
 551  
 552          foreach ( $all_themes as $theme_slug => $theme ) {
 553              ++$themes_total;
 554  
 555              if ( array_key_exists( $theme_slug, $theme_updates ) ) {
 556                  ++$themes_need_updates;
 557              }
 558          }
 559  
 560          // If this is a child theme, increase the allowed theme count by one, to account for the parent.
 561          if ( is_child_theme() ) {
 562              ++$allowed_theme_count;
 563          }
 564  
 565          // If there's a default theme installed and not in use, we count that as allowed as well.
 566          if ( $has_default_theme && ! $using_default_theme ) {
 567              ++$allowed_theme_count;
 568          }
 569  
 570          if ( $themes_total > $allowed_theme_count ) {
 571              $has_unused_themes = true;
 572              $themes_inactive   = ( $themes_total - $allowed_theme_count );
 573          }
 574  
 575          // Check if any themes need to be updated.
 576          if ( $themes_need_updates > 0 ) {
 577              $result['status'] = 'critical';
 578  
 579              $result['label'] = __( 'You have themes waiting to be updated' );
 580  
 581              $result['description'] .= sprintf(
 582                  '<p>%s</p>',
 583                  sprintf(
 584                      /* translators: %d: The number of outdated themes. */
 585                      _n(
 586                          'Your site has %d theme waiting to be updated.',
 587                          'Your site has %d themes waiting to be updated.',
 588                          $themes_need_updates
 589                      ),
 590                      $themes_need_updates
 591                  )
 592              );
 593          } else {
 594              // Give positive feedback about the site being good about keeping things up to date.
 595              if ( 1 === $themes_total ) {
 596                  $result['description'] .= sprintf(
 597                      '<p>%s</p>',
 598                      __( 'Your site has 1 installed theme, and it is up to date.' )
 599                  );
 600              } elseif ( $themes_total > 0 ) {
 601                  $result['description'] .= sprintf(
 602                      '<p>%s</p>',
 603                      sprintf(
 604                          /* translators: %d: The number of themes. */
 605                          _n(
 606                              'Your site has %d installed theme, and it is up to date.',
 607                              'Your site has %d installed themes, and they are all up to date.',
 608                              $themes_total
 609                          ),
 610                          $themes_total
 611                      )
 612                  );
 613              } else {
 614                  $result['description'] .= sprintf(
 615                      '<p>%s</p>',
 616                      __( 'Your site does not have any installed themes.' )
 617                  );
 618              }
 619          }
 620  
 621          if ( $has_unused_themes && ! is_multisite() ) {
 622  
 623              // This is a child theme, so we want to be a bit more explicit in our messages.
 624              if ( $active_theme->parent() ) {
 625                  // Recommend removing inactive themes, except a default theme, your current one, and the parent theme.
 626                  $result['status'] = 'recommended';
 627  
 628                  $result['label'] = __( 'You should remove inactive themes' );
 629  
 630                  if ( $using_default_theme ) {
 631                      $result['description'] .= sprintf(
 632                          '<p>%s %s</p>',
 633                          sprintf(
 634                              /* translators: %d: The number of inactive themes. */
 635                              _n(
 636                                  'Your site has %d inactive theme.',
 637                                  'Your site has %d inactive themes.',
 638                                  $themes_inactive
 639                              ),
 640                              $themes_inactive
 641                          ),
 642                          sprintf(
 643                              /* translators: 1: The currently active theme. 2: The active theme's parent theme. */
 644                              __( 'To enhance your site&#8217;s security, you should consider removing any themes you are not using. You should keep your active theme, %1$s, and %2$s, its parent theme.' ),
 645                              $active_theme->name,
 646                              $active_theme->parent()->name
 647                          )
 648                      );
 649                  } else {
 650                      $result['description'] .= sprintf(
 651                          '<p>%s %s</p>',
 652                          sprintf(
 653                              /* translators: %d: The number of inactive themes. */
 654                              _n(
 655                                  'Your site has %d inactive theme.',
 656                                  'Your site has %d inactive themes.',
 657                                  $themes_inactive
 658                              ),
 659                              $themes_inactive
 660                          ),
 661                          sprintf(
 662                              /* translators: 1: The default theme for WordPress. 2: The currently active theme. 3: The active theme's parent theme. */
 663                              __( 'To enhance your site&#8217;s security, you should consider removing any themes you are not using. You should keep %1$s, the default WordPress theme, %2$s, your active theme, and %3$s, its parent theme.' ),
 664                              $default_theme ? $default_theme->name : WP_DEFAULT_THEME,
 665                              $active_theme->name,
 666                              $active_theme->parent()->name
 667                          )
 668                      );
 669                  }
 670              } else {
 671                  // Recommend removing all inactive themes.
 672                  $result['status'] = 'recommended';
 673  
 674                  $result['label'] = __( 'You should remove inactive themes' );
 675  
 676                  if ( $using_default_theme ) {
 677                      $result['description'] .= sprintf(
 678                          '<p>%s %s</p>',
 679                          sprintf(
 680                              /* translators: 1: The amount of inactive themes. 2: The currently active theme. */
 681                              _n(
 682                                  'Your site has %1$d inactive theme, other than %2$s, your active theme.',
 683                                  'Your site has %1$d inactive themes, other than %2$s, your active theme.',
 684                                  $themes_inactive
 685                              ),
 686                              $themes_inactive,
 687                              $active_theme->name
 688                          ),
 689                          __( 'You should consider removing any unused themes to enhance your site&#8217;s security.' )
 690                      );
 691                  } else {
 692                      $result['description'] .= sprintf(
 693                          '<p>%s %s</p>',
 694                          sprintf(
 695                              /* translators: 1: The amount of inactive themes. 2: The default theme for WordPress. 3: The currently active theme. */
 696                              _n(
 697                                  'Your site has %1$d inactive theme, other than %2$s, the default WordPress theme, and %3$s, your active theme.',
 698                                  'Your site has %1$d inactive themes, other than %2$s, the default WordPress theme, and %3$s, your active theme.',
 699                                  $themes_inactive
 700                              ),
 701                              $themes_inactive,
 702                              $default_theme ? $default_theme->name : WP_DEFAULT_THEME,
 703                              $active_theme->name
 704                          ),
 705                          __( 'You should consider removing any unused themes to enhance your site&#8217;s security.' )
 706                      );
 707                  }
 708              }
 709          }
 710  
 711          // If no default Twenty* theme exists.
 712          if ( ! $has_default_theme ) {
 713              $result['status'] = 'recommended';
 714  
 715              $result['label'] = __( 'Have a default theme available' );
 716  
 717              $result['description'] .= sprintf(
 718                  '<p>%s</p>',
 719                  __( 'Your site does not have any default theme. Default themes are used by WordPress automatically if anything is wrong with your chosen theme.' )
 720              );
 721          }
 722  
 723          return $result;
 724      }
 725  
 726      /**
 727       * Tests if the supplied PHP version is supported.
 728       *
 729       * @since 5.2.0
 730       *
 731       * @return array The test results.
 732       */
 733  	public function get_test_php_version() {
 734          $response = wp_check_php_version();
 735  
 736          $result = array(
 737              'label'       => sprintf(
 738                  /* translators: %s: The server PHP version. */
 739                  __( 'Your site is running PHP %s' ),
 740                  PHP_VERSION
 741              ),
 742              'status'      => 'good',
 743              'badge'       => array(
 744                  'label' => __( 'Performance' ),
 745                  'color' => 'blue',
 746              ),
 747              'description' => sprintf(
 748                  '<p>%s</p>',
 749                  __( 'PHP is one of the programming languages used to build WordPress. Newer versions of PHP receive regular security updates and may increase your site&#8217;s performance.' )
 750              ),
 751              'actions'     => sprintf(
 752                  '<p><a href="%s" target="_blank">%s<span class="screen-reader-text"> %s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
 753                  esc_url( wp_get_update_php_url() ),
 754                  __( 'Learn more about updating PHP' ),
 755                  /* translators: Hidden accessibility text. */
 756                  __( '(opens in a new tab)' )
 757              ),
 758              'test'        => 'php_version',
 759          );
 760  
 761          if ( ! $response ) {
 762              $result['label'] = sprintf(
 763                  /* translators: %s: The server PHP version. */
 764                  __( 'Unable to determine the status of the current PHP version (%s)' ),
 765                  PHP_VERSION
 766              );
 767              $result['status']      = 'recommended';
 768              $result['description'] = '<p><em>' . sprintf(
 769                  /* translators: %s is the URL to the Serve Happy docs page. */
 770                  __( 'Unable to access the WordPress.org API for <a href="%s">Serve Happy</a>.' ),
 771                  'https://codex.wordpress.org/WordPress.org_API#Serve_Happy'
 772              ) . '</em></p>' . $result['description'];
 773              return $result;
 774          }
 775  
 776          $result['description'] .= '<p>' . sprintf(
 777              /* translators: %s: The minimum recommended PHP version. */
 778              __( 'The minimum recommended version of PHP is %s.' ),
 779              $response['recommended_version']
 780          ) . '</p>';
 781  
 782          // PHP is up to date.
 783          if ( version_compare( PHP_VERSION, $response['recommended_version'], '>=' ) ) {
 784              $result['label'] = sprintf(
 785                  /* translators: %s: The server PHP version. */
 786                  __( 'Your site is running a recommended version of PHP (%s)' ),
 787                  PHP_VERSION
 788              );
 789              $result['status'] = 'good';
 790  
 791              return $result;
 792          }
 793  
 794          // The PHP version is older than the recommended version, but still receiving active support.
 795          if ( $response['is_supported'] ) {
 796              $result['label'] = sprintf(
 797                  /* translators: %s: The server PHP version. */
 798                  __( 'Your site is running on an older version of PHP (%s)' ),
 799                  PHP_VERSION
 800              );
 801              $result['status'] = 'recommended';
 802  
 803              return $result;
 804          }
 805  
 806          /*
 807           * The PHP version is still receiving security fixes, but is lower than
 808           * the expected minimum version that will be required by WordPress in the near future.
 809           */
 810          if ( $response['is_secure'] && $response['is_lower_than_future_minimum'] ) {
 811              // The `is_secure` array key name doesn't actually imply this is a secure version of PHP. It only means it receives security updates.
 812  
 813              $result['label'] = sprintf(
 814                  /* translators: %s: The server PHP version. */
 815                  __( 'Your site is running on an outdated version of PHP (%s), which soon will not be supported by WordPress.' ),
 816                  PHP_VERSION
 817              );
 818  
 819              $result['status']         = 'critical';
 820              $result['badge']['label'] = __( 'Requirements' );
 821  
 822              return $result;
 823          }
 824  
 825          // The PHP version is only receiving security fixes.
 826          if ( $response['is_secure'] ) {
 827              $result['label'] = sprintf(
 828                  /* translators: %s: The server PHP version. */
 829                  __( 'Your site is running on an older version of PHP (%s), which should be updated' ),
 830                  PHP_VERSION
 831              );
 832              $result['status'] = 'recommended';
 833  
 834              return $result;
 835          }
 836  
 837          // No more security updates for the PHP version, and lower than the expected minimum version required by WordPress.
 838          if ( $response['is_lower_than_future_minimum'] ) {
 839              $message = sprintf(
 840                  /* translators: %s: The server PHP version. */
 841                  __( 'Your site is running on an outdated version of PHP (%s), which does not receive security updates and soon will not be supported by WordPress.' ),
 842                  PHP_VERSION
 843              );
 844          } else {
 845              // No more security updates for the PHP version, must be updated.
 846              $message = sprintf(
 847                  /* translators: %s: The server PHP version. */
 848                  __( 'Your site is running on an outdated version of PHP (%s), which does not receive security updates. It should be updated.' ),
 849                  PHP_VERSION
 850              );
 851          }
 852  
 853          $result['label']  = $message;
 854          $result['status'] = 'critical';
 855  
 856          $result['badge']['label'] = __( 'Security' );
 857  
 858          return $result;
 859      }
 860  
 861      /**
 862       * Checks if the passed extension or function are available.
 863       *
 864       * Make the check for available PHP modules into a simple boolean operator for a cleaner test runner.
 865       *
 866       * @since 5.2.0
 867       * @since 5.3.0 The `$constant_name` and `$class_name` parameters were added.
 868       *
 869       * @param string $extension_name Optional. The extension name to test. Default null.
 870       * @param string $function_name  Optional. The function name to test. Default null.
 871       * @param string $constant_name  Optional. The constant name to test for. Default null.
 872       * @param string $class_name     Optional. The class name to test for. Default null.
 873       * @return bool Whether or not the extension and function are available.
 874       */
 875  	private function test_php_extension_availability( $extension_name = null, $function_name = null, $constant_name = null, $class_name = null ) {
 876          // If no extension or function is passed, claim to fail testing, as we have nothing to test against.
 877          if ( ! $extension_name && ! $function_name && ! $constant_name && ! $class_name ) {
 878              return false;
 879          }
 880  
 881          if ( $extension_name && ! extension_loaded( $extension_name ) ) {
 882              return false;
 883          }
 884  
 885          if ( $function_name && ! function_exists( $function_name ) ) {
 886              return false;
 887          }
 888  
 889          if ( $constant_name && ! defined( $constant_name ) ) {
 890              return false;
 891          }
 892  
 893          if ( $class_name && ! class_exists( $class_name ) ) {
 894              return false;
 895          }
 896  
 897          return true;
 898      }
 899  
 900      /**
 901       * Tests if required PHP modules are installed on the host.
 902       *
 903       * This test builds on the recommendations made by the WordPress Hosting Team
 904       * as seen at https://make.wordpress.org/hosting/handbook/handbook/server-environment/#php-extensions
 905       *
 906       * @since 5.2.0
 907       *
 908       * @return array
 909       */
 910  	public function get_test_php_extensions() {
 911          $result = array(
 912              'label'       => __( 'Required and recommended modules are installed' ),
 913              'status'      => 'good',
 914              'badge'       => array(
 915                  'label' => __( 'Performance' ),
 916                  'color' => 'blue',
 917              ),
 918              'description' => sprintf(
 919                  '<p>%s</p><p>%s</p>',
 920                  __( 'PHP modules perform most of the tasks on the server that make your site run. Any changes to these must be made by your server administrator.' ),
 921                  sprintf(
 922                      /* translators: 1: Link to the hosting group page about recommended PHP modules. 2: Additional link attributes. 3: Accessibility text. */
 923                      __( 'The WordPress Hosting Team maintains a list of those modules, both recommended and required, in <a href="%1$s" %2$s>the team handbook%3$s</a>.' ),
 924                      /* translators: Localized team handbook, if one exists. */
 925                      esc_url( __( 'https://make.wordpress.org/hosting/handbook/handbook/server-environment/#php-extensions' ) ),
 926                      'target="_blank"',
 927                      sprintf(
 928                          '<span class="screen-reader-text"> %s</span><span aria-hidden="true" class="dashicons dashicons-external"></span>',
 929                          /* translators: Hidden accessibility text. */
 930                          __( '(opens in a new tab)' )
 931                      )
 932                  )
 933              ),
 934              'actions'     => '',
 935              'test'        => 'php_extensions',
 936          );
 937  
 938          $modules = array(
 939              'curl'      => array(
 940                  'function' => 'curl_version',
 941                  'required' => false,
 942              ),
 943              'dom'       => array(
 944                  'class'    => 'DOMNode',
 945                  'required' => false,
 946              ),
 947              'exif'      => array(
 948                  'function' => 'exif_read_data',
 949                  'required' => false,
 950              ),
 951              'fileinfo'  => array(
 952                  'function' => 'finfo_file',
 953                  'required' => false,
 954              ),
 955              'hash'      => array(
 956                  'function' => 'hash',
 957                  'required' => true,
 958              ),
 959              'imagick'   => array(
 960                  'extension' => 'imagick',
 961                  'required'  => false,
 962              ),
 963              'json'      => array(
 964                  'function' => 'json_last_error',
 965                  'required' => true,
 966              ),
 967              'mbstring'  => array(
 968                  'function' => 'mb_check_encoding',
 969                  'required' => false,
 970              ),
 971              'mysqli'    => array(
 972                  'function' => 'mysqli_connect',
 973                  'required' => false,
 974              ),
 975              // Sodium was introduced in PHP 7.2, but the extension may not be enabled.
 976              'libsodium' => array(
 977                  'constant'            => 'SODIUM_LIBRARY_VERSION',
 978                  'required'            => false,
 979                  'php_bundled_version' => '7.2.0',
 980              ),
 981              'openssl'   => array(
 982                  'function' => 'openssl_encrypt',
 983                  'required' => false,
 984              ),
 985              'pcre'      => array(
 986                  'function' => 'preg_match',
 987                  'required' => false,
 988              ),
 989              'mod_xml'   => array(
 990                  'extension' => 'libxml',
 991                  'required'  => false,
 992              ),
 993              'zip'       => array(
 994                  'class'    => 'ZipArchive',
 995                  'required' => false,
 996              ),
 997              'filter'    => array(
 998                  'function' => 'filter_list',
 999                  'required' => false,
1000              ),
1001              'gd'        => array(
1002                  'extension'    => 'gd',
1003                  'required'     => false,
1004                  'fallback_for' => 'imagick',
1005              ),
1006              'iconv'     => array(
1007                  'function' => 'iconv',
1008                  'required' => false,
1009              ),
1010              'intl'      => array(
1011                  'extension' => 'intl',
1012                  'required'  => false,
1013              ),
1014              'mcrypt'    => array(
1015                  'extension'    => 'mcrypt',
1016                  'required'     => false,
1017                  'fallback_for' => 'libsodium',
1018              ),
1019              'simplexml' => array(
1020                  'extension'    => 'simplexml',
1021                  'required'     => false,
1022                  'fallback_for' => 'mod_xml',
1023              ),
1024              'xmlreader' => array(
1025                  'extension'    => 'xmlreader',
1026                  'required'     => false,
1027                  'fallback_for' => 'mod_xml',
1028              ),
1029              'zlib'      => array(
1030                  'extension'    => 'zlib',
1031                  'required'     => false,
1032                  'fallback_for' => 'zip',
1033              ),
1034          );
1035  
1036          /**
1037           * Filters the array representing all the modules we wish to test for.
1038           *
1039           * @since 5.2.0
1040           * @since 5.3.0 The `$constant` and `$class` parameters were added.
1041           *
1042           * @param array $modules {
1043           *     An associative array of modules to test for.
1044           *
1045           *     @type array ...$0 {
1046           *         An associative array of module properties used during testing.
1047           *         One of either `$function` or `$extension` must be provided, or they will fail by default.
1048           *
1049           *         @type string $function     Optional. A function name to test for the existence of.
1050           *         @type string $extension    Optional. An extension to check if is loaded in PHP.
1051           *         @type string $constant     Optional. A constant name to check for to verify an extension exists.
1052           *         @type string $class        Optional. A class name to check for to verify an extension exists.
1053           *         @type bool   $required     Is this a required feature or not.
1054           *         @type string $fallback_for Optional. The module this module replaces as a fallback.
1055           *     }
1056           * }
1057           */
1058          $modules = apply_filters( 'site_status_test_php_modules', $modules );
1059  
1060          $failures = array();
1061  
1062          foreach ( $modules as $library => $module ) {
1063              $extension_name = $module['extension'] ?? null;
1064              $function_name  = $module['function'] ?? null;
1065              $constant_name  = $module['constant'] ?? null;
1066              $class_name     = $module['class'] ?? null;
1067  
1068              // If this module is a fallback for another function, check if that other function passed.
1069              if ( isset( $module['fallback_for'] ) ) {
1070                  /*
1071                   * If that other function has a failure, mark this module as required for usual operations.
1072                   * If that other function hasn't failed, skip this test as it's only a fallback.
1073                   */
1074                  if ( isset( $failures[ $module['fallback_for'] ] ) ) {
1075                      $module['required'] = true;
1076                  } else {
1077                      continue;
1078                  }
1079              }
1080  
1081              if ( ! $this->test_php_extension_availability( $extension_name, $function_name, $constant_name, $class_name )
1082                  && ( ! isset( $module['php_bundled_version'] )
1083                      || version_compare( PHP_VERSION, $module['php_bundled_version'], '<' ) )
1084              ) {
1085                  if ( $module['required'] ) {
1086                      $result['status'] = 'critical';
1087  
1088                      $class = 'error';
1089                      /* translators: Hidden accessibility text. */
1090                      $screen_reader = __( 'Error' );
1091                      $message       = sprintf(
1092                          /* translators: %s: The module name. */
1093                          __( 'The required module, %s, is not installed, or has been disabled.' ),
1094                          $library
1095                      );
1096                  } else {
1097                      $class = 'warning';
1098                      /* translators: Hidden accessibility text. */
1099                      $screen_reader = __( 'Warning' );
1100                      $message       = sprintf(
1101                          /* translators: %s: The module name. */
1102                          __( 'The optional module, %s, is not installed, or has been disabled.' ),
1103                          $library
1104                      );
1105                  }
1106  
1107                  if ( ! $module['required'] && 'good' === $result['status'] ) {
1108                      $result['status'] = 'recommended';
1109                  }
1110  
1111                  $failures[ $library ] = "<span class='dashicons $class' aria-hidden='true'></span><span class='screen-reader-text'>$screen_reader</span> $message";
1112              }
1113          }
1114  
1115          if ( ! empty( $failures ) ) {
1116              $output = '<ul>';
1117  
1118              foreach ( $failures as $failure ) {
1119                  $output .= sprintf(
1120                      '<li>%s</li>',
1121                      $failure
1122                  );
1123              }
1124  
1125              $output .= '</ul>';
1126          }
1127  
1128          if ( 'good' !== $result['status'] ) {
1129              if ( 'recommended' === $result['status'] ) {
1130                  $result['label'] = __( 'One or more recommended modules are missing' );
1131              }
1132              if ( 'critical' === $result['status'] ) {
1133                  $result['label'] = __( 'One or more required modules are missing' );
1134              }
1135  
1136              $result['description'] .= $output;
1137          }
1138  
1139          return $result;
1140      }
1141  
1142      /**
1143       * Tests if the PHP default timezone is set to UTC.
1144       *
1145       * @since 5.3.1
1146       *
1147       * @return array The test results.
1148       */
1149  	public function get_test_php_default_timezone() {
1150          $result = array(
1151              'label'       => __( 'PHP default timezone is valid' ),
1152              'status'      => 'good',
1153              'badge'       => array(
1154                  'label' => __( 'Performance' ),
1155                  'color' => 'blue',
1156              ),
1157              'description' => sprintf(
1158                  '<p>%s</p>',
1159                  __( 'PHP default timezone was configured by WordPress on loading. This is necessary for correct calculations of dates and times.' )
1160              ),
1161              'actions'     => '',
1162              'test'        => 'php_default_timezone',
1163          );
1164  
1165          if ( 'UTC' !== date_default_timezone_get() ) {
1166              $result['status'] = 'critical';
1167  
1168              $result['label'] = __( 'PHP default timezone is invalid' );
1169  
1170              $result['description'] = sprintf(
1171                  '<p>%s</p>',
1172                  sprintf(
1173                      /* translators: %s: date_default_timezone_set() */
1174                      __( 'PHP default timezone was changed after WordPress loading by a %s function call. This interferes with correct calculations of dates and times.' ),
1175                      '<code>date_default_timezone_set()</code>'
1176                  )
1177              );
1178          }
1179  
1180          return $result;
1181      }
1182  
1183      /**
1184       * Tests if there's an active PHP session that can affect loopback requests.
1185       *
1186       * @since 5.5.0
1187       *
1188       * @return array The test results.
1189       */
1190  	public function get_test_php_sessions() {
1191          $result = array(
1192              'label'       => __( 'No PHP sessions detected' ),
1193              'status'      => 'good',
1194              'badge'       => array(
1195                  'label' => __( 'Performance' ),
1196                  'color' => 'blue',
1197              ),
1198              'description' => sprintf(
1199                  '<p>%s</p>',
1200                  sprintf(
1201                      /* translators: 1: session_start(), 2: session_write_close() */
1202                      __( 'PHP sessions created by a %1$s function call may interfere with REST API and loopback requests. An active session should be closed by %2$s before making any HTTP requests.' ),
1203                      '<code>session_start()</code>',
1204                      '<code>session_write_close()</code>'
1205                  )
1206              ),
1207              'test'        => 'php_sessions',
1208          );
1209  
1210          if ( function_exists( 'session_status' ) && PHP_SESSION_ACTIVE === session_status() ) {
1211              $result['status'] = 'critical';
1212  
1213              $result['label'] = __( 'An active PHP session was detected' );
1214  
1215              $result['description'] = sprintf(
1216                  '<p>%s</p>',
1217                  sprintf(
1218                      /* translators: 1: session_start(), 2: session_write_close() */
1219                      __( 'A PHP session was created by a %1$s function call. This interferes with REST API and loopback requests. The session should be closed by %2$s before making any HTTP requests.' ),
1220                      '<code>session_start()</code>',
1221                      '<code>session_write_close()</code>'
1222                  )
1223              );
1224          }
1225  
1226          return $result;
1227      }
1228  
1229      /**
1230       * Tests if the SQL server is up to date.
1231       *
1232       * @since 5.2.0
1233       *
1234       * @return array The test results.
1235       */
1236  	public function get_test_sql_server() {
1237          if ( ! $this->mysql_server_version ) {
1238              $this->prepare_sql_data();
1239          }
1240  
1241          $result = array(
1242              'label'       => __( 'SQL server is up to date' ),
1243              'status'      => 'good',
1244              'badge'       => array(
1245                  'label' => __( 'Performance' ),
1246                  'color' => 'blue',
1247              ),
1248              'description' => sprintf(
1249                  '<p>%s</p>',
1250                  __( 'The SQL server is a required piece of software for the database WordPress uses to store all your site&#8217;s content and settings.' )
1251              ),
1252              'actions'     => sprintf(
1253                  '<p><a href="%s" target="_blank">%s<span class="screen-reader-text"> %s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
1254                  /* translators: Localized version of WordPress requirements if one exists. */
1255                  esc_url( __( 'https://wordpress.org/about/requirements/' ) ),
1256                  __( 'Learn more about what WordPress requires to run.' ),
1257                  /* translators: Hidden accessibility text. */
1258                  __( '(opens in a new tab)' )
1259              ),
1260              'test'        => 'sql_server',
1261          );
1262  
1263          $db_dropin = file_exists( WP_CONTENT_DIR . '/db.php' );
1264  
1265          if ( ! $this->is_recommended_mysql_version ) {
1266              $result['status'] = 'recommended';
1267  
1268              $result['label'] = __( 'Outdated SQL server' );
1269  
1270              $result['description'] .= sprintf(
1271                  '<p>%s</p>',
1272                  sprintf(
1273                      /* translators: 1: The database engine in use (MySQL or MariaDB). 2: Database server recommended version number. */
1274                      __( 'For optimal performance and security reasons, you should consider running %1$s version %2$s or higher. Contact your web hosting company to correct this.' ),
1275                      ( $this->is_mariadb ? 'MariaDB' : 'MySQL' ),
1276                      $this->mysql_recommended_version
1277                  )
1278              );
1279          }
1280  
1281          if ( ! $this->is_acceptable_mysql_version ) {
1282              $result['status'] = 'critical';
1283  
1284              $result['label']          = __( 'Severely outdated SQL server' );
1285              $result['badge']['label'] = __( 'Security' );
1286  
1287              $result['description'] .= sprintf(
1288                  '<p>%s</p>',
1289                  sprintf(
1290                      /* translators: 1: The database engine in use (MySQL or MariaDB). 2: Database server minimum version number. */
1291                      __( 'WordPress requires %1$s version %2$s or higher. Contact your web hosting company to correct this.' ),
1292                      ( $this->is_mariadb ? 'MariaDB' : 'MySQL' ),
1293                      $this->mysql_required_version
1294                  )
1295              );
1296          }
1297  
1298          if ( $db_dropin ) {
1299              $result['description'] .= sprintf(
1300                  '<p>%s</p>',
1301                  wp_kses(
1302                      sprintf(
1303                          /* translators: 1: The name of the drop-in. 2: The name of the database engine. */
1304                          __( 'You are using a %1$s drop-in which might mean that a %2$s database is not being used.' ),
1305                          '<code>wp-content/db.php</code>',
1306                          ( $this->is_mariadb ? 'MariaDB' : 'MySQL' )
1307                      ),
1308                      array(
1309                          'code' => true,
1310                      )
1311                  )
1312              );
1313          }
1314  
1315          return $result;
1316      }
1317  
1318      /**
1319       * Tests if the site can communicate with WordPress.org.
1320       *
1321       * @since 5.2.0
1322       *
1323       * @return array The test results.
1324       */
1325  	public function get_test_dotorg_communication() {
1326          $result = array(
1327              'label'       => __( 'Can communicate with WordPress.org' ),
1328              'status'      => '',
1329              'badge'       => array(
1330                  'label' => __( 'Security' ),
1331                  'color' => 'blue',
1332              ),
1333              'description' => sprintf(
1334                  '<p>%s</p>',
1335                  __( 'Communicating with the WordPress servers is used to check for new versions, and to both install and update WordPress core, themes or plugins.' )
1336              ),
1337              'actions'     => '',
1338              'test'        => 'dotorg_communication',
1339          );
1340  
1341          $wp_dotorg = wp_remote_get(
1342              'https://api.wordpress.org',
1343              array(
1344                  'timeout' => 10,
1345              )
1346          );
1347          if ( ! is_wp_error( $wp_dotorg ) ) {
1348              $result['status'] = 'good';
1349          } else {
1350              $result['status'] = 'critical';
1351  
1352              $result['label'] = __( 'Could not reach WordPress.org' );
1353  
1354              $result['description'] .= sprintf(
1355                  '<p>%s</p>',
1356                  sprintf(
1357                      '<span class="dashicons error" aria-hidden="true"></span><span class="screen-reader-text">%s</span> %s',
1358                      /* translators: Hidden accessibility text. */
1359                      __( 'Error' ),
1360                      sprintf(
1361                          /* translators: 1: The IP address WordPress.org resolves to. 2: The error returned by the lookup. */
1362                          __( 'Your site is unable to reach WordPress.org at %1$s, and returned the error: %2$s' ),
1363                          gethostbyname( 'api.wordpress.org' ),
1364                          $wp_dotorg->get_error_message()
1365                      )
1366                  )
1367              );
1368  
1369              $result['actions'] = sprintf(
1370                  '<p><a href="%s" target="_blank">%s<span class="screen-reader-text"> %s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
1371                  /* translators: Localized Support reference. */
1372                  esc_url( __( 'https://wordpress.org/support/forums/' ) ),
1373                  __( 'Get help resolving this issue.' ),
1374                  /* translators: Hidden accessibility text. */
1375                  __( '(opens in a new tab)' )
1376              );
1377          }
1378  
1379          return $result;
1380      }
1381  
1382      /**
1383       * Tests if debug information is enabled.
1384       *
1385       * When WP_DEBUG is enabled, errors and information may be disclosed to site visitors,
1386       * or logged to a publicly accessible file.
1387       *
1388       * Debugging is also frequently left enabled after looking for errors on a site,
1389       * as site owners do not understand the implications of this.
1390       *
1391       * @since 5.2.0
1392       *
1393       * @return array The test results.
1394       */
1395  	public function get_test_is_in_debug_mode() {
1396          $result = array(
1397              'label'       => __( 'Your site is not set to output debug information' ),
1398              'status'      => 'good',
1399              'badge'       => array(
1400                  'label' => __( 'Security' ),
1401                  'color' => 'blue',
1402              ),
1403              'description' => sprintf(
1404                  '<p>%s</p>',
1405                  __( 'Debug mode is often enabled to gather more details about an error or site failure, but may contain sensitive information which should not be available on a publicly available website.' )
1406              ),
1407              'actions'     => sprintf(
1408                  '<p><a href="%s" target="_blank">%s<span class="screen-reader-text"> %s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
1409                  /* translators: Documentation explaining debugging in WordPress. */
1410                  esc_url( __( 'https://developer.wordpress.org/advanced-administration/debug/debug-wordpress/' ) ),
1411                  __( 'Learn more about debugging in WordPress.' ),
1412                  /* translators: Hidden accessibility text. */
1413                  __( '(opens in a new tab)' )
1414              ),
1415              'test'        => 'is_in_debug_mode',
1416          );
1417  
1418          if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
1419              if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
1420                  $result['label'] = __( 'Your site is set to log errors to a potentially public file' );
1421  
1422                  $result['status'] = str_starts_with( ini_get( 'error_log' ), ABSPATH ) ? 'critical' : 'recommended';
1423  
1424                  $result['description'] .= sprintf(
1425                      '<p>%s</p>',
1426                      sprintf(
1427                          /* translators: %s: WP_DEBUG_LOG */
1428                          __( 'The value, %s, has been added to this website&#8217;s configuration file. This means any errors on the site will be written to a file which is potentially available to all users.' ),
1429                          '<code>WP_DEBUG_LOG</code>'
1430                      )
1431                  );
1432              }
1433  
1434              if ( defined( 'WP_DEBUG_DISPLAY' ) && WP_DEBUG_DISPLAY ) {
1435                  $result['label'] = __( 'Your site is set to display errors to site visitors' );
1436  
1437                  $result['status'] = 'critical';
1438  
1439                  // On development environments, set the status to recommended.
1440                  if ( $this->is_development_environment() ) {
1441                      $result['status'] = 'recommended';
1442                  }
1443  
1444                  $result['description'] .= sprintf(
1445                      '<p>%s</p>',
1446                      sprintf(
1447                          /* translators: 1: WP_DEBUG_DISPLAY, 2: WP_DEBUG */
1448                          __( 'The value, %1$s, has either been enabled by %2$s or added to your configuration file. This will make errors display on the front end of your site.' ),
1449                          '<code>WP_DEBUG_DISPLAY</code>',
1450                          '<code>WP_DEBUG</code>'
1451                      )
1452                  );
1453              }
1454          }
1455  
1456          return $result;
1457      }
1458  
1459      /**
1460       * Tests if the site is serving content over HTTPS.
1461       *
1462       * Many sites have varying degrees of HTTPS support, the most common of which is sites that have it
1463       * enabled, but only if you visit the right site address.
1464       *
1465       * @since 5.2.0
1466       * @since 5.7.0 Updated to rely on {@see wp_is_using_https()} and {@see wp_is_https_supported()}.
1467       *
1468       * @return array The test results.
1469       */
1470  	public function get_test_https_status() {
1471          /*
1472           * Check HTTPS detection results.
1473           */
1474          $errors = wp_get_https_detection_errors();
1475  
1476          $default_update_url = wp_get_default_update_https_url();
1477  
1478          $result = array(
1479              'label'       => __( 'Your website is using an active HTTPS connection' ),
1480              'status'      => 'good',
1481              'badge'       => array(
1482                  'label' => __( 'Security' ),
1483                  'color' => 'blue',
1484              ),
1485              'description' => sprintf(
1486                  '<p>%s</p>',
1487                  __( 'An HTTPS connection is a more secure way of browsing the web. Many services now have HTTPS as a requirement. HTTPS allows you to take advantage of new features that can increase site speed, improve search rankings, and gain the trust of your visitors by helping to protect their online privacy.' )
1488              ),
1489              'actions'     => sprintf(
1490                  '<p><a href="%s" target="_blank">%s<span class="screen-reader-text"> %s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
1491                  esc_url( $default_update_url ),
1492                  __( 'Learn more about why you should use HTTPS' ),
1493                  /* translators: Hidden accessibility text. */
1494                  __( '(opens in a new tab)' )
1495              ),
1496              'test'        => 'https_status',
1497          );
1498  
1499          if ( ! wp_is_using_https() ) {
1500              /*
1501               * If the website is not using HTTPS, provide more information
1502               * about whether it is supported and how it can be enabled.
1503               */
1504              $result['status'] = 'recommended';
1505              $result['label']  = __( 'Your website does not use HTTPS' );
1506  
1507              if ( wp_is_site_url_using_https() ) {
1508                  if ( is_ssl() ) {
1509                      $result['description'] = sprintf(
1510                          '<p>%s</p>',
1511                          sprintf(
1512                              /* translators: %s: URL to Settings > General > Site Address. */
1513                              __( 'You are accessing this website using HTTPS, but your <a href="%s">Site Address</a> is not set up to use HTTPS by default.' ),
1514                              esc_url( admin_url( 'options-general.php' ) . '#home' )
1515                          )
1516                      );
1517                  } else {
1518                      $result['description'] = sprintf(
1519                          '<p>%s</p>',
1520                          sprintf(
1521                              /* translators: %s: URL to Settings > General > Site Address. */
1522                              __( 'Your <a href="%s">Site Address</a> is not set up to use HTTPS.' ),
1523                              esc_url( admin_url( 'options-general.php' ) . '#home' )
1524                          )
1525                      );
1526                  }
1527              } else {
1528                  if ( is_ssl() ) {
1529                      $result['description'] = sprintf(
1530                          '<p>%s</p>',
1531                          sprintf(
1532                              /* translators: 1: URL to Settings > General > WordPress Address, 2: URL to Settings > General > Site Address. */
1533                              __( 'You are accessing this website using HTTPS, but your <a href="%1$s">WordPress Address</a> and <a href="%2$s">Site Address</a> are not set up to use HTTPS by default.' ),
1534                              esc_url( admin_url( 'options-general.php' ) . '#siteurl' ),
1535                              esc_url( admin_url( 'options-general.php' ) . '#home' )
1536                          )
1537                      );
1538                  } else {
1539                      $result['description'] = sprintf(
1540                          '<p>%s</p>',
1541                          sprintf(
1542                              /* translators: 1: URL to Settings > General > WordPress Address, 2: URL to Settings > General > Site Address. */
1543                              __( 'Your <a href="%1$s">WordPress Address</a> and <a href="%2$s">Site Address</a> are not set up to use HTTPS.' ),
1544                              esc_url( admin_url( 'options-general.php' ) . '#siteurl' ),
1545                              esc_url( admin_url( 'options-general.php' ) . '#home' )
1546                          )
1547                      );
1548                  }
1549              }
1550  
1551              if ( wp_is_https_supported() ) {
1552                  $result['description'] .= sprintf(
1553                      '<p>%s</p>',
1554                      __( 'HTTPS is already supported for your website.' )
1555                  );
1556  
1557                  if ( defined( 'WP_HOME' ) || defined( 'WP_SITEURL' ) ) {
1558                      $result['description'] .= sprintf(
1559                          '<p>%s</p>',
1560                          sprintf(
1561                              /* translators: 1: wp-config.php, 2: WP_HOME, 3: WP_SITEURL */
1562                              __( 'However, your WordPress Address is currently controlled by a PHP constant and therefore cannot be updated. You need to edit your %1$s and remove or update the definitions of %2$s and %3$s.' ),
1563                              '<code>wp-config.php</code>',
1564                              '<code>WP_HOME</code>',
1565                              '<code>WP_SITEURL</code>'
1566                          )
1567                      );
1568                  } elseif ( current_user_can( 'update_https' ) ) {
1569                      $default_direct_update_url = add_query_arg( 'action', 'update_https', wp_nonce_url( admin_url( 'site-health.php' ), 'wp_update_https' ) );
1570                      $direct_update_url         = wp_get_direct_update_https_url();
1571  
1572                      if ( ! empty( $direct_update_url ) ) {
1573                          $result['actions'] = sprintf(
1574                              '<p class="button-container"><a class="button button-primary" href="%1$s" target="_blank">%2$s<span class="screen-reader-text"> %3$s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
1575                              esc_url( $direct_update_url ),
1576                              __( 'Update your site to use HTTPS' ),
1577                              /* translators: Hidden accessibility text. */
1578                              __( '(opens in a new tab)' )
1579                          );
1580                      } else {
1581                          $result['actions'] = sprintf(
1582                              '<p class="button-container"><a class="button button-primary" href="%1$s">%2$s</a></p>',
1583                              esc_url( $default_direct_update_url ),
1584                              __( 'Update your site to use HTTPS' )
1585                          );
1586                      }
1587                  }
1588              } else {
1589                  // If host-specific "Update HTTPS" URL is provided, include a link.
1590                  $update_url = wp_get_update_https_url();
1591                  if ( $update_url !== $default_update_url ) {
1592                      $result['description'] .= sprintf(
1593                          '<p><a href="%s" target="_blank">%s<span class="screen-reader-text"> %s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
1594                          esc_url( $update_url ),
1595                          __( 'Talk to your web host about supporting HTTPS for your website.' ),
1596                          /* translators: Hidden accessibility text. */
1597                          __( '(opens in a new tab)' )
1598                      );
1599                  } else {
1600                      $result['description'] .= sprintf(
1601                          '<p>%s</p>',
1602                          __( 'Talk to your web host about supporting HTTPS for your website.' )
1603                      );
1604                  }
1605              }
1606          }
1607  
1608          return $result;
1609      }
1610  
1611      /**
1612       * Checks if the HTTP API can handle SSL/TLS requests.
1613       *
1614       * @since 5.2.0
1615       *
1616       * @return array The test result.
1617       */
1618  	public function get_test_ssl_support() {
1619          $result = array(
1620              'label'       => '',
1621              'status'      => '',
1622              'badge'       => array(
1623                  'label' => __( 'Security' ),
1624                  'color' => 'blue',
1625              ),
1626              'description' => sprintf(
1627                  '<p>%s</p>',
1628                  __( 'Securely communicating between servers are needed for transactions such as fetching files, conducting sales on store sites, and much more.' )
1629              ),
1630              'actions'     => '',
1631              'test'        => 'ssl_support',
1632          );
1633  
1634          $supports_https = wp_http_supports( array( 'ssl' ) );
1635  
1636          if ( $supports_https ) {
1637              $result['status'] = 'good';
1638  
1639              $result['label'] = __( 'Your site can communicate securely with other services' );
1640          } else {
1641              $result['status'] = 'critical';
1642  
1643              $result['label'] = __( 'Your site is unable to communicate securely with other services' );
1644  
1645              $result['description'] .= sprintf(
1646                  '<p>%s</p>',
1647                  __( 'Talk to your web host about OpenSSL support for PHP.' )
1648              );
1649          }
1650  
1651          return $result;
1652      }
1653  
1654      /**
1655       * Tests if scheduled events run as intended.
1656       *
1657       * If scheduled events are not running, this may indicate something with WP_Cron is not working
1658       * as intended, or that there are orphaned events hanging around from older code.
1659       *
1660       * @since 5.2.0
1661       *
1662       * @return array The test results.
1663       */
1664  	public function get_test_scheduled_events() {
1665          $result = array(
1666              'label'       => __( 'Scheduled events are running' ),
1667              'status'      => 'good',
1668              'badge'       => array(
1669                  'label' => __( 'Performance' ),
1670                  'color' => 'blue',
1671              ),
1672              'description' => sprintf(
1673                  '<p>%s</p>',
1674                  __( 'Scheduled events are what periodically looks for updates to plugins, themes and WordPress itself. It is also what makes sure scheduled posts are published on time. It may also be used by various plugins to make sure that planned actions are executed.' )
1675              ),
1676              'actions'     => '',
1677              'test'        => 'scheduled_events',
1678          );
1679  
1680          $this->wp_schedule_test_init();
1681  
1682          if ( is_wp_error( $this->has_missed_cron() ) ) {
1683              $result['status'] = 'critical';
1684  
1685              $result['label'] = __( 'It was not possible to check your scheduled events' );
1686  
1687              $result['description'] = sprintf(
1688                  '<p>%s</p>',
1689                  sprintf(
1690                      /* translators: %s: The error message returned while from the cron scheduler. */
1691                      __( 'While trying to test your site&#8217;s scheduled events, the following error was returned: %s' ),
1692                      $this->has_missed_cron()->get_error_message()
1693                  )
1694              );
1695          } elseif ( $this->has_missed_cron() ) {
1696              $result['status'] = 'recommended';
1697  
1698              $result['label'] = __( 'A scheduled event has failed' );
1699  
1700              $result['description'] = sprintf(
1701                  '<p>%s</p>',
1702                  sprintf(
1703                      /* translators: %s: The name of the failed cron event. */
1704                      __( 'The scheduled event, %s, failed to run. Your site still works, but this may indicate that scheduling posts or automated updates may not work as intended.' ),
1705                      $this->last_missed_cron
1706                  )
1707              );
1708          } elseif ( $this->has_late_cron() ) {
1709              $result['status'] = 'recommended';
1710  
1711              $result['label'] = __( 'A scheduled event is late' );
1712  
1713              $result['description'] = sprintf(
1714                  '<p>%s</p>',
1715                  sprintf(
1716                      /* translators: %s: The name of the late cron event. */
1717                      __( 'The scheduled event, %s, is late to run. Your site still works, but this may indicate that scheduling posts or automated updates may not work as intended.' ),
1718                      $this->last_late_cron
1719                  )
1720              );
1721          }
1722  
1723          return $result;
1724      }
1725  
1726      /**
1727       * Tests if WordPress can run automated background updates.
1728       *
1729       * Background updates in WordPress are primarily used for minor releases and security updates.
1730       * It's important to either have these working, or be aware that they are intentionally disabled
1731       * for whatever reason.
1732       *
1733       * @since 5.2.0
1734       *
1735       * @return array The test results.
1736       */
1737  	public function get_test_background_updates() {
1738          $result = array(
1739              'label'       => __( 'Background updates are working' ),
1740              'status'      => 'good',
1741              'badge'       => array(
1742                  'label' => __( 'Security' ),
1743                  'color' => 'blue',
1744              ),
1745              'description' => sprintf(
1746                  '<p>%s</p>',
1747                  __( 'Background updates ensure that WordPress can auto-update if a security update is released for the version you are currently using.' )
1748              ),
1749              'actions'     => '',
1750              'test'        => 'background_updates',
1751          );
1752  
1753          if ( ! class_exists( 'WP_Site_Health_Auto_Updates' ) ) {
1754              require_once  ABSPATH . 'wp-admin/includes/class-wp-site-health-auto-updates.php';
1755          }
1756  
1757          /*
1758           * Run the auto-update tests in a separate class,
1759           * as there are many considerations to be made.
1760           */
1761          $automatic_updates = new WP_Site_Health_Auto_Updates();
1762          $tests             = $automatic_updates->run_tests();
1763  
1764          $output = '<ul>';
1765  
1766          foreach ( $tests as $test ) {
1767              /* translators: Hidden accessibility text. */
1768              $severity_string = __( 'Passed' );
1769  
1770              if ( 'fail' === $test->severity ) {
1771                  $result['label'] = __( 'Background updates are not working as expected' );
1772  
1773                  $result['status'] = 'critical';
1774  
1775                  /* translators: Hidden accessibility text. */
1776                  $severity_string = __( 'Error' );
1777              }
1778  
1779              if ( 'warning' === $test->severity && 'good' === $result['status'] ) {
1780                  $result['label'] = __( 'Background updates may not be working properly' );
1781  
1782                  $result['status'] = 'recommended';
1783  
1784                  /* translators: Hidden accessibility text. */
1785                  $severity_string = __( 'Warning' );
1786              }
1787  
1788              $output .= sprintf(
1789                  '<li><span class="dashicons %s"><span class="screen-reader-text">%s</span></span> %s</li>',
1790                  esc_attr( $test->severity ),
1791                  $severity_string,
1792                  $test->description
1793              );
1794          }
1795  
1796          $output .= '</ul>';
1797  
1798          if ( 'good' !== $result['status'] ) {
1799              $result['description'] .= $output;
1800          }
1801  
1802          return $result;
1803      }
1804  
1805      /**
1806       * Tests if plugin and theme auto-updates appear to be configured correctly.
1807       *
1808       * @since 5.5.0
1809       *
1810       * @return array The test results.
1811       */
1812  	public function get_test_plugin_theme_auto_updates() {
1813          $result = array(
1814              'label'       => __( 'Plugin and theme auto-updates appear to be configured correctly' ),
1815              'status'      => 'good',
1816              'badge'       => array(
1817                  'label' => __( 'Security' ),
1818                  'color' => 'blue',
1819              ),
1820              'description' => sprintf(
1821                  '<p>%s</p>',
1822                  __( 'Plugin and theme auto-updates ensure that the latest versions are always installed.' )
1823              ),
1824              'actions'     => '',
1825              'test'        => 'plugin_theme_auto_updates',
1826          );
1827  
1828          $check_plugin_theme_updates = $this->detect_plugin_theme_auto_update_issues();
1829  
1830          $result['status'] = $check_plugin_theme_updates->status;
1831  
1832          if ( 'good' !== $result['status'] ) {
1833              $result['label'] = __( 'Your site may have problems auto-updating plugins and themes' );
1834  
1835              $result['description'] .= sprintf(
1836                  '<p>%s</p>',
1837                  $check_plugin_theme_updates->message
1838              );
1839          }
1840  
1841          return $result;
1842      }
1843  
1844      /**
1845       * Tests available disk space for updates.
1846       *
1847       * @since 6.3.0
1848       *
1849       * @return array The test results.
1850       */
1851  	public function get_test_available_updates_disk_space() {
1852          $available_space = function_exists( 'disk_free_space' ) ? @disk_free_space( WP_CONTENT_DIR ) : false;
1853  
1854          $result = array(
1855              'label'       => __( 'Disk space available to safely perform updates' ),
1856              'status'      => 'good',
1857              'badge'       => array(
1858                  'label' => __( 'Security' ),
1859                  'color' => 'blue',
1860              ),
1861              'description' => sprintf(
1862                  /* translators: %s: Available disk space in MB or GB. */
1863                  '<p>' . __( '%s available disk space was detected, update routines can be performed safely.' ) . '</p>',
1864                  size_format( $available_space )
1865              ),
1866              'actions'     => '',
1867              'test'        => 'available_updates_disk_space',
1868          );
1869  
1870          if ( false === $available_space ) {
1871              $result['description'] = __( 'Could not determine available disk space for updates.' );
1872              $result['status']      = 'recommended';
1873          } elseif ( $available_space < 20 * MB_IN_BYTES ) {
1874              $result['description'] = sprintf(
1875                  /* translators: %s: Available disk space in MB or GB. */
1876                  __( 'Available disk space is critically low, less than %s available. Proceed with caution, updates may fail.' ),
1877                  size_format( 20 * MB_IN_BYTES )
1878              );
1879              $result['status'] = 'critical';
1880          } elseif ( $available_space < 100 * MB_IN_BYTES ) {
1881              $result['description'] = sprintf(
1882                  /* translators: %s: Available disk space in MB or GB. */
1883                  __( 'Available disk space is low, less than %s available.' ),
1884                  size_format( 100 * MB_IN_BYTES )
1885              );
1886              $result['status'] = 'recommended';
1887          }
1888  
1889          return $result;
1890      }
1891  
1892      /**
1893       * Tests if registration is open to everyone and the default role is privileged.
1894       *
1895       * @since 7.0.0
1896       *
1897       * @return array The test results.
1898       */
1899  	public function get_test_insecure_registration() {
1900          $users_can_register = get_option( 'users_can_register' );
1901          $default_role       = get_option( 'default_role' );
1902  
1903          $result = array(
1904              'label'       => __( 'New users are not given a privileged role' ),
1905              'status'      => 'good',
1906              'badge'       => array(
1907                  'label' => __( 'Security' ),
1908                  'color' => 'blue',
1909              ),
1910              'description' => '<p>' . __( 'The combination of open registration setting and the default user role may lead to security issues.' ) . '</p>',
1911              'actions'     => '',
1912              'test'        => 'insecure_registration',
1913          );
1914  
1915          if ( $users_can_register && in_array( $default_role, array( 'editor', 'administrator' ), true ) ) {
1916              $result['label']       = __( 'Open registration with a privileged default role' );
1917              $result['description'] = '<p>' . __( 'Registration is open to anyone, and the default role is set to a privileged role.' ) . '</p>';
1918              $result['status']      = 'critical';
1919              $result['actions']     = sprintf(
1920                  '<p><a href="%s">%s</a></p>',
1921                  esc_url( admin_url( 'options-general.php' ) ),
1922                  __( 'Change these settings' )
1923              );
1924          }
1925  
1926          return $result;
1927      }
1928  
1929      /**
1930       * Tests if plugin and theme temporary backup directories are writable or can be created.
1931       *
1932       * @since 6.3.0
1933       *
1934       * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
1935       *
1936       * @return array The test results.
1937       */
1938  	public function get_test_update_temp_backup_writable() {
1939          global $wp_filesystem;
1940  
1941          $result = array(
1942              'label'       => __( 'Plugin and theme temporary backup directory is writable' ),
1943              'status'      => 'good',
1944              'badge'       => array(
1945                  'label' => __( 'Security' ),
1946                  'color' => 'blue',
1947              ),
1948              'description' => sprintf(
1949                  /* translators: %s: wp-content/upgrade-temp-backup */
1950                  '<p>' . __( 'The %s directory used to improve the stability of plugin and theme updates is writable.' ) . '</p>',
1951                  '<code>wp-content/upgrade-temp-backup</code>'
1952              ),
1953              'actions'     => '',
1954              'test'        => 'update_temp_backup_writable',
1955          );
1956  
1957          if ( ! function_exists( 'WP_Filesystem' ) ) {
1958              require_once  ABSPATH . 'wp-admin/includes/file.php';
1959          }
1960  
1961          ob_start();
1962          $credentials = request_filesystem_credentials( '' );
1963          ob_end_clean();
1964  
1965          if ( false === $credentials || ! WP_Filesystem( $credentials ) ) {
1966              $result['status']      = 'recommended';
1967              $result['label']       = __( 'Could not access filesystem' );
1968              $result['description'] = __( 'Unable to connect to the filesystem. Please confirm your credentials.' );
1969              return $result;
1970          }
1971  
1972          $wp_content = $wp_filesystem->wp_content_dir();
1973  
1974          if ( ! $wp_content ) {
1975              $result['status']      = 'critical';
1976              $result['label']       = __( 'Unable to locate WordPress content directory' );
1977              $result['description'] = sprintf(
1978                  /* translators: %s: wp-content */
1979                  '<p>' . __( 'The %s directory cannot be located.' ) . '</p>',
1980                  '<code>wp-content</code>'
1981              );
1982              return $result;
1983          }
1984  
1985          $upgrade_dir_exists      = $wp_filesystem->is_dir( "$wp_content/upgrade" );
1986          $upgrade_dir_is_writable = $wp_filesystem->is_writable( "$wp_content/upgrade" );
1987          $backup_dir_exists       = $wp_filesystem->is_dir( "$wp_content/upgrade-temp-backup" );
1988          $backup_dir_is_writable  = $wp_filesystem->is_writable( "$wp_content/upgrade-temp-backup" );
1989  
1990          $plugins_dir_exists      = $wp_filesystem->is_dir( "$wp_content/upgrade-temp-backup/plugins" );
1991          $plugins_dir_is_writable = $wp_filesystem->is_writable( "$wp_content/upgrade-temp-backup/plugins" );
1992          $themes_dir_exists       = $wp_filesystem->is_dir( "$wp_content/upgrade-temp-backup/themes" );
1993          $themes_dir_is_writable  = $wp_filesystem->is_writable( "$wp_content/upgrade-temp-backup/themes" );
1994  
1995          if ( $plugins_dir_exists && ! $plugins_dir_is_writable && $themes_dir_exists && ! $themes_dir_is_writable ) {
1996              $result['status']      = 'critical';
1997              $result['label']       = __( 'Plugin and theme temporary backup directories exist but are not writable' );
1998              $result['description'] = sprintf(
1999                  /* translators: 1: wp-content/upgrade-temp-backup/plugins, 2: wp-content/upgrade-temp-backup/themes. */
2000                  '<p>' . __( 'The %1$s and %2$s directories exist but are not writable. These directories are used to improve the stability of plugin updates. Please make sure the server has write permissions to these directories.' ) . '</p>',
2001                  '<code>wp-content/upgrade-temp-backup/plugins</code>',
2002                  '<code>wp-content/upgrade-temp-backup/themes</code>'
2003              );
2004              return $result;
2005          }
2006  
2007          if ( $plugins_dir_exists && ! $plugins_dir_is_writable ) {
2008              $result['status']      = 'critical';
2009              $result['label']       = __( 'Plugin temporary backup directory exists but is not writable' );
2010              $result['description'] = sprintf(
2011                  /* translators: %s: wp-content/upgrade-temp-backup/plugins */
2012                  '<p>' . __( 'The %s directory exists but is not writable. This directory is used to improve the stability of plugin updates. Please make sure the server has write permissions to this directory.' ) . '</p>',
2013                  '<code>wp-content/upgrade-temp-backup/plugins</code>'
2014              );
2015              return $result;
2016          }
2017  
2018          if ( $themes_dir_exists && ! $themes_dir_is_writable ) {
2019              $result['status']      = 'critical';
2020              $result['label']       = __( 'Theme temporary backup directory exists but is not writable' );
2021              $result['description'] = sprintf(
2022                  /* translators: %s: wp-content/upgrade-temp-backup/themes */
2023                  '<p>' . __( 'The %s directory exists but is not writable. This directory is used to improve the stability of theme updates. Please make sure the server has write permissions to this directory.' ) . '</p>',
2024                  '<code>wp-content/upgrade-temp-backup/themes</code>'
2025              );
2026              return $result;
2027          }
2028  
2029          if ( ( ! $plugins_dir_exists || ! $themes_dir_exists ) && $backup_dir_exists && ! $backup_dir_is_writable ) {
2030              $result['status']      = 'critical';
2031              $result['label']       = __( 'The temporary backup directory exists but is not writable' );
2032              $result['description'] = sprintf(
2033                  /* translators: %s: wp-content/upgrade-temp-backup */
2034                  '<p>' . __( 'The %s directory exists but is not writable. This directory is used to improve the stability of plugin and theme updates. Please make sure the server has write permissions to this directory.' ) . '</p>',
2035                  '<code>wp-content/upgrade-temp-backup</code>'
2036              );
2037              return $result;
2038          }
2039  
2040          if ( ! $backup_dir_exists && $upgrade_dir_exists && ! $upgrade_dir_is_writable ) {
2041              $result['status']      = 'critical';
2042              $result['label']       = __( 'The upgrade directory exists but is not writable' );
2043              $result['description'] = sprintf(
2044                  /* translators: %s: wp-content/upgrade */
2045                  '<p>' . __( 'The %s directory exists but is not writable. This directory is used for plugin and theme updates. Please make sure the server has write permissions to this directory.' ) . '</p>',
2046                  '<code>wp-content/upgrade</code>'
2047              );
2048              return $result;
2049          }
2050  
2051          if ( ! $upgrade_dir_exists && ! $wp_filesystem->is_writable( $wp_content ) ) {
2052              $result['status']      = 'critical';
2053              $result['label']       = __( 'The upgrade directory cannot be created' );
2054              $result['description'] = sprintf(
2055                  /* translators: 1: wp-content/upgrade, 2: wp-content. */
2056                  '<p>' . __( 'The %1$s directory does not exist, and the server does not have write permissions in %2$s to create it. This directory is used for plugin and theme updates. Please make sure the server has write permissions in %2$s.' ) . '</p>',
2057                  '<code>wp-content/upgrade</code>',
2058                  '<code>wp-content</code>'
2059              );
2060              return $result;
2061          }
2062  
2063          return $result;
2064      }
2065  
2066      /**
2067       * Tests if loopbacks work as expected.
2068       *
2069       * A loopback is when WordPress queries itself, for example to start a new WP_Cron instance,
2070       * or when editing a plugin or theme. This has shown itself to be a recurring issue,
2071       * as code can very easily break this interaction.
2072       *
2073       * @since 5.2.0
2074       *
2075       * @return array The test results.
2076       */
2077  	public function get_test_loopback_requests() {
2078          $result = array(
2079              'label'       => __( 'Your site can perform loopback requests' ),
2080              'status'      => 'good',
2081              'badge'       => array(
2082                  'label' => __( 'Performance' ),
2083                  'color' => 'blue',
2084              ),
2085              'description' => sprintf(
2086                  '<p>%s</p>',
2087                  __( 'Loopback requests are used to run scheduled events, and are also used by the built-in editors for themes and plugins to verify code stability.' )
2088              ),
2089              'actions'     => '',
2090              'test'        => 'loopback_requests',
2091          );
2092  
2093          $check_loopback = $this->can_perform_loopback();
2094  
2095          $result['status'] = $check_loopback->status;
2096  
2097          if ( 'good' !== $result['status'] ) {
2098              $result['label'] = __( 'Your site could not complete a loopback request' );
2099  
2100              $result['description'] .= sprintf(
2101                  '<p>%s</p>',
2102                  $check_loopback->message
2103              );
2104          }
2105  
2106          return $result;
2107      }
2108  
2109      /**
2110       * Tests if HTTP requests are blocked.
2111       *
2112       * It's possible to block all outgoing communication (with the possibility of allowing certain
2113       * hosts) via the HTTP API. This may create problems for users as many features are running as
2114       * services these days.
2115       *
2116       * @since 5.2.0
2117       *
2118       * @return array The test results.
2119       */
2120  	public function get_test_http_requests() {
2121          $result = array(
2122              'label'       => __( 'HTTP requests seem to be working as expected' ),
2123              'status'      => 'good',
2124              'badge'       => array(
2125                  'label' => __( 'Performance' ),
2126                  'color' => 'blue',
2127              ),
2128              'description' => sprintf(
2129                  '<p>%s</p>',
2130                  __( 'It is possible for site maintainers to block all, or some, communication to other sites and services. If set up incorrectly, this may prevent plugins and themes from working as intended.' )
2131              ),
2132              'actions'     => '',
2133              'test'        => 'http_requests',
2134          );
2135  
2136          $blocked = false;
2137          $hosts   = array();
2138  
2139          if ( defined( 'WP_HTTP_BLOCK_EXTERNAL' ) && WP_HTTP_BLOCK_EXTERNAL ) {
2140              $blocked = true;
2141          }
2142  
2143          if ( defined( 'WP_ACCESSIBLE_HOSTS' ) ) {
2144              $hosts = explode( ',', WP_ACCESSIBLE_HOSTS );
2145          }
2146  
2147          if ( $blocked && 0 === count( $hosts ) ) {
2148              $result['status'] = 'critical';
2149  
2150              $result['label'] = __( 'HTTP requests are blocked' );
2151  
2152              $result['description'] .= sprintf(
2153                  '<p>%s</p>',
2154                  sprintf(
2155                      /* translators: %s: Name of the constant used. */
2156                      __( 'HTTP requests have been blocked by the %s constant, with no allowed hosts.' ),
2157                      '<code>WP_HTTP_BLOCK_EXTERNAL</code>'
2158                  )
2159              );
2160          }
2161  
2162          if ( $blocked && 0 < count( $hosts ) ) {
2163              $result['status'] = 'recommended';
2164  
2165              $result['label'] = __( 'HTTP requests are partially blocked' );
2166  
2167              $result['description'] .= sprintf(
2168                  '<p>%s</p>',
2169                  sprintf(
2170                      /* translators: 1: Name of the constant used. 2: List of allowed hostnames. */
2171                      __( 'HTTP requests have been blocked by the %1$s constant, with some allowed hosts: %2$s.' ),
2172                      '<code>WP_HTTP_BLOCK_EXTERNAL</code>',
2173                      implode( ',', $hosts )
2174                  )
2175              );
2176          }
2177  
2178          return $result;
2179      }
2180  
2181      /**
2182       * Tests if the REST API is accessible.
2183       *
2184       * Various security measures may block the REST API from working, or it may have been disabled in general.
2185       * This is required for the new block editor to work, so we explicitly test for this.
2186       *
2187       * @since 5.2.0
2188       *
2189       * @return array The test results.
2190       */
2191  	public function get_test_rest_availability() {
2192          $result = array(
2193              'label'       => __( 'The REST API is available' ),
2194              'status'      => 'good',
2195              'badge'       => array(
2196                  'label' => __( 'Performance' ),
2197                  'color' => 'blue',
2198              ),
2199              'description' => sprintf(
2200                  '<p>%s</p>',
2201                  __( 'The REST API is one way that WordPress and other applications communicate with the server. For example, the block editor screen relies on the REST API to display and save your posts and pages.' )
2202              ),
2203              'actions'     => '',
2204              'test'        => 'rest_availability',
2205          );
2206  
2207          $cookies = wp_unslash( $_COOKIE );
2208          $timeout = 10; // 10 seconds.
2209          $headers = array(
2210              'Cache-Control' => 'no-cache',
2211              'X-WP-Nonce'    => wp_create_nonce( 'wp_rest' ),
2212          );
2213          // Include Basic auth in loopback requests.
2214          if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
2215              $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
2216          }
2217  
2218          $url = rest_url( 'wp/v2/types/post' );
2219  
2220          // The context for this is editing with the new block editor.
2221          $url = add_query_arg(
2222              array(
2223                  'context' => 'edit',
2224              ),
2225              $url
2226          );
2227  
2228          /** This filter is documented in wp-includes/class-wp-http-streams.php */
2229          $sslverify = apply_filters( 'https_local_ssl_verify', false, $url );
2230  
2231          $r = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) );
2232  
2233          if ( is_wp_error( $r ) ) {
2234              $result['status'] = 'critical';
2235  
2236              $result['label'] = __( 'The REST API encountered an error' );
2237  
2238              $result['description'] .= sprintf(
2239                  '<p>%s</p><p>%s<br>%s</p>',
2240                  __( 'When testing the REST API, an error was encountered:' ),
2241                  sprintf(
2242                      // translators: %s: The REST API URL.
2243                      __( 'REST API Endpoint: %s' ),
2244                      $url
2245                  ),
2246                  sprintf(
2247                      // translators: 1: The WordPress error code. 2: The WordPress error message.
2248                      __( 'REST API Response: (%1$s) %2$s' ),
2249                      $r->get_error_code(),
2250                      $r->get_error_message()
2251                  )
2252              );
2253          } elseif ( 200 !== wp_remote_retrieve_response_code( $r ) ) {
2254              $result['status'] = 'recommended';
2255  
2256              $result['label'] = __( 'The REST API encountered an unexpected result' );
2257  
2258              $result['description'] .= sprintf(
2259                  '<p>%s</p><p>%s<br>%s</p>',
2260                  __( 'When testing the REST API, an unexpected result was returned:' ),
2261                  sprintf(
2262                      // translators: %s: The REST API URL.
2263                      __( 'REST API Endpoint: %s' ),
2264                      $url
2265                  ),
2266                  sprintf(
2267                      // translators: 1: The WordPress error code. 2: The HTTP status code error message.
2268                      __( 'REST API Response: (%1$s) %2$s' ),
2269                      wp_remote_retrieve_response_code( $r ),
2270                      wp_remote_retrieve_response_message( $r )
2271                  )
2272              );
2273          } else {
2274              $json = json_decode( wp_remote_retrieve_body( $r ), true );
2275  
2276              if ( false !== $json && ! isset( $json['capabilities'] ) ) {
2277                  $result['status'] = 'recommended';
2278  
2279                  $result['label'] = __( 'The REST API did not behave correctly' );
2280  
2281                  $result['description'] .= sprintf(
2282                      '<p>%s</p>',
2283                      sprintf(
2284                          /* translators: %s: The name of the query parameter being tested. */
2285                          __( 'The REST API did not process the %s query parameter correctly.' ),
2286                          '<code>context</code>'
2287                      )
2288                  );
2289              }
2290          }
2291  
2292          return $result;
2293      }
2294  
2295      /**
2296       * Tests if 'file_uploads' directive in PHP.ini is turned off.
2297       *
2298       * @since 5.5.0
2299       *
2300       * @return array The test results.
2301       */
2302  	public function get_test_file_uploads() {
2303          $result = array(
2304              'label'       => __( 'Files can be uploaded' ),
2305              'status'      => 'good',
2306              'badge'       => array(
2307                  'label' => __( 'Performance' ),
2308                  'color' => 'blue',
2309              ),
2310              'description' => sprintf(
2311                  '<p>%s</p>',
2312                  sprintf(
2313                      /* translators: 1: file_uploads, 2: php.ini */
2314                      __( 'The %1$s directive in %2$s determines if uploading files is allowed on your site.' ),
2315                      '<code>file_uploads</code>',
2316                      '<code>php.ini</code>'
2317                  )
2318              ),
2319              'actions'     => '',
2320              'test'        => 'file_uploads',
2321          );
2322  
2323          if ( empty( ini_get( 'file_uploads' ) ) ) {
2324              $result['status']       = 'critical';
2325              $result['description'] .= sprintf(
2326                  '<p>%s</p>',
2327                  sprintf(
2328                      /* translators: 1: file_uploads, 2: 0 */
2329                      __( '%1$s is set to %2$s. You won\'t be able to upload files on your site.' ),
2330                      '<code>file_uploads</code>',
2331                      '<code>0</code>'
2332                  )
2333              );
2334              return $result;
2335          }
2336  
2337          $post_max_size       = ini_get( 'post_max_size' );
2338          $upload_max_filesize = ini_get( 'upload_max_filesize' );
2339  
2340          if ( wp_convert_hr_to_bytes( $post_max_size ) < wp_convert_hr_to_bytes( $upload_max_filesize ) ) {
2341              $result['label'] = sprintf(
2342                  /* translators: 1: post_max_size, 2: upload_max_filesize */
2343                  __( 'The "%1$s" value is smaller than "%2$s"' ),
2344                  'post_max_size',
2345                  'upload_max_filesize'
2346              );
2347              $result['status'] = 'recommended';
2348  
2349              if ( 0 === wp_convert_hr_to_bytes( $post_max_size ) ) {
2350                  $result['description'] = sprintf(
2351                      '<p>%s</p>',
2352                      sprintf(
2353                          /* translators: 1: post_max_size, 2: upload_max_filesize */
2354                          __( 'The setting for %1$s is currently configured as 0, this could cause some problems when trying to upload files through plugin or theme features that rely on various upload methods. It is recommended to configure this setting to a fixed value, ideally matching the value of %2$s, as some upload methods read the value 0 as either unlimited, or disabled.' ),
2355                          '<code>post_max_size</code>',
2356                          '<code>upload_max_filesize</code>'
2357                      )
2358                  );
2359              } else {
2360                  $result['description'] = sprintf(
2361                      '<p>%s</p>',
2362                      sprintf(
2363                          /* translators: 1: post_max_size, 2: upload_max_filesize */
2364                          __( 'The setting for %1$s is smaller than %2$s, this could cause some problems when trying to upload files.' ),
2365                          '<code>post_max_size</code>',
2366                          '<code>upload_max_filesize</code>'
2367                      )
2368                  );
2369              }
2370  
2371              return $result;
2372          }
2373  
2374          return $result;
2375      }
2376  
2377      /**
2378       * Tests if the Authorization header has the expected values.
2379       *
2380       * @since 5.6.0
2381       *
2382       * @return array
2383       */
2384  	public function get_test_authorization_header() {
2385          $result = array(
2386              'label'       => __( 'The Authorization header is working as expected' ),
2387              'status'      => 'good',
2388              'badge'       => array(
2389                  'label' => __( 'Security' ),
2390                  'color' => 'blue',
2391              ),
2392              'description' => sprintf(
2393                  '<p>%s</p>',
2394                  __( 'The Authorization header is used by third-party applications you have approved for this site. Without this header, those apps cannot connect to your site.' )
2395              ),
2396              'actions'     => '',
2397              'test'        => 'authorization_header',
2398          );
2399  
2400          if ( ! isset( $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] ) ) {
2401              $result['label'] = __( 'The authorization header is missing' );
2402          } elseif ( 'user' !== $_SERVER['PHP_AUTH_USER'] || 'pwd' !== $_SERVER['PHP_AUTH_PW'] ) {
2403              $result['label'] = __( 'The authorization header is invalid' );
2404          } else {
2405              return $result;
2406          }
2407  
2408          $result['status']       = 'recommended';
2409          $result['description'] .= sprintf(
2410              '<p>%s</p>',
2411              __( 'If you are still seeing this warning after having tried the actions below, you may need to contact your hosting provider for further assistance.' )
2412          );
2413  
2414          if ( ! function_exists( 'got_mod_rewrite' ) ) {
2415              require_once  ABSPATH . 'wp-admin/includes/misc.php';
2416          }
2417  
2418          if ( got_mod_rewrite() ) {
2419              $result['actions'] .= sprintf(
2420                  '<p><a href="%s">%s</a></p>',
2421                  esc_url( admin_url( 'options-permalink.php' ) ),
2422                  __( 'Flush permalinks' )
2423              );
2424          } else {
2425              $result['actions'] .= sprintf(
2426                  '<p><a href="%s" target="_blank">%s<span class="screen-reader-text"> %s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
2427                  __( 'https://developer.wordpress.org/rest-api/frequently-asked-questions/#why-is-authentication-not-working' ),
2428                  __( 'Learn how to configure the Authorization header.' ),
2429                  /* translators: Hidden accessibility text. */
2430                  __( '(opens in a new tab)' )
2431              );
2432          }
2433  
2434          return $result;
2435      }
2436  
2437      /**
2438       * Tests if a full page cache is available.
2439       *
2440       * @since 6.1.0
2441       *
2442       * @return array The test result.
2443       */
2444  	public function get_test_page_cache() {
2445          $description  = '<p>' . __( 'Page cache enhances the speed and performance of your site by saving and serving static pages instead of calling for a page every time a user visits.' ) . '</p>';
2446          $description .= '<p>' . __( 'Page cache is detected by looking for an active page cache plugin as well as making three requests to the homepage and looking for one or more of the following HTTP client caching response headers:' ) . '</p>';
2447          $description .= '<code>' . implode( '</code>, <code>', array_keys( $this->get_page_cache_headers() ) ) . '.</code>';
2448  
2449          $result = array(
2450              'badge'       => array(
2451                  'label' => __( 'Performance' ),
2452                  'color' => 'blue',
2453              ),
2454              'description' => wp_kses_post( $description ),
2455              'test'        => 'page_cache',
2456              'status'      => 'good',
2457              'label'       => '',
2458              'actions'     => sprintf(
2459                  '<p><a href="%1$s" target="_blank" rel="noreferrer">%2$s<span class="screen-reader-text"> %3$s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
2460                  __( 'https://developer.wordpress.org/advanced-administration/performance/optimization/#caching' ),
2461                  __( 'Learn more about page cache' ),
2462                  /* translators: Hidden accessibility text. */
2463                  __( '(opens in a new tab)' )
2464              ),
2465          );
2466  
2467          $page_cache_detail = $this->get_page_cache_detail();
2468  
2469          if ( is_wp_error( $page_cache_detail ) ) {
2470              $result['label']  = __( 'Unable to detect the presence of page cache' );
2471              $result['status'] = 'recommended';
2472              $error_info       = sprintf(
2473              /* translators: 1: Error message, 2: Error code. */
2474                  __( 'Unable to detect page cache due to possible loopback request problem. Please verify that the loopback request test is passing. Error: %1$s (Code: %2$s)' ),
2475                  $page_cache_detail->get_error_message(),
2476                  $page_cache_detail->get_error_code()
2477              );
2478              $result['description'] = wp_kses_post( "<p>$error_info</p>" ) . $result['description'];
2479              return $result;
2480          }
2481  
2482          $result['status'] = $page_cache_detail['status'];
2483  
2484          switch ( $page_cache_detail['status'] ) {
2485              case 'recommended':
2486                  $result['label'] = __( 'Page cache is not detected but the server response time is OK' );
2487                  break;
2488              case 'good':
2489                  $result['label'] = __( 'Page cache is detected and the server response time is good' );
2490                  break;
2491              default:
2492                  if ( empty( $page_cache_detail['headers'] ) && ! $page_cache_detail['advanced_cache_present'] ) {
2493                      $result['label'] = __( 'Page cache is not detected and the server response time is slow' );
2494                  } else {
2495                      $result['label'] = __( 'Page cache is detected but the server response time is still slow' );
2496                  }
2497          }
2498  
2499          $page_cache_test_summary = array();
2500  
2501          if ( empty( $page_cache_detail['response_time'] ) ) {
2502              $page_cache_test_summary[] = '<span class="dashicons dashicons-dismiss" aria-hidden="true"></span> ' . __( 'Server response time could not be determined. Verify that loopback requests are working.' );
2503          } else {
2504  
2505              $threshold = $this->get_good_response_time_threshold();
2506              if ( $page_cache_detail['response_time'] < $threshold ) {
2507                  $page_cache_test_summary[] = '<span class="dashicons dashicons-yes-alt" aria-hidden="true"></span> ' . sprintf(
2508                      /* translators: 1: The response time in milliseconds, 2: The recommended threshold in milliseconds. */
2509                      __( 'Median server response time was %1$s milliseconds. This is less than the recommended %2$s milliseconds threshold.' ),
2510                      number_format_i18n( $page_cache_detail['response_time'] ),
2511                      number_format_i18n( $threshold )
2512                  );
2513              } else {
2514                  $page_cache_test_summary[] = '<span class="dashicons dashicons-warning" aria-hidden="true"></span> ' . sprintf(
2515                      /* translators: 1: The response time in milliseconds, 2: The recommended threshold in milliseconds. */
2516                      __( 'Median server response time was %1$s milliseconds. It should be less than the recommended %2$s milliseconds threshold.' ),
2517                      number_format_i18n( $page_cache_detail['response_time'] ),
2518                      number_format_i18n( $threshold )
2519                  );
2520              }
2521  
2522              if ( empty( $page_cache_detail['headers'] ) ) {
2523                  $page_cache_test_summary[] = '<span class="dashicons dashicons-warning" aria-hidden="true"></span> ' . __( 'No client caching response headers were detected.' );
2524              } else {
2525                  $headers_summary  = '<span class="dashicons dashicons-yes-alt" aria-hidden="true"></span>';
2526                  $headers_summary .= ' ' . sprintf(
2527                      /* translators: %d: Number of caching headers. */
2528                      _n(
2529                          'There was %d client caching response header detected:',
2530                          'There were %d client caching response headers detected:',
2531                          count( $page_cache_detail['headers'] )
2532                      ),
2533                      count( $page_cache_detail['headers'] )
2534                  );
2535                  $headers_summary          .= ' <code>' . implode( '</code>, <code>', $page_cache_detail['headers'] ) . '</code>.';
2536                  $page_cache_test_summary[] = $headers_summary;
2537              }
2538          }
2539  
2540          if ( $page_cache_detail['advanced_cache_present'] ) {
2541              $page_cache_test_summary[] = '<span class="dashicons dashicons-yes-alt" aria-hidden="true"></span> ' . __( 'A page cache plugin was detected.' );
2542          } elseif ( ! ( is_array( $page_cache_detail ) && ! empty( $page_cache_detail['headers'] ) ) ) {
2543              // Note: This message is not shown if client caching response headers were present since an external caching layer may be employed.
2544              $page_cache_test_summary[] = '<span class="dashicons dashicons-warning" aria-hidden="true"></span> ' . __( 'A page cache plugin was not detected.' );
2545          }
2546  
2547          $result['description'] .= '<ul><li>' . implode( '</li><li>', $page_cache_test_summary ) . '</li></ul>';
2548          return $result;
2549      }
2550  
2551      /**
2552       * Tests if the site uses persistent object cache and recommends to use it if not.
2553       *
2554       * @since 6.1.0
2555       *
2556       * @return array The test result.
2557       */
2558  	public function get_test_persistent_object_cache() {
2559          /**
2560           * Filters the action URL for the persistent object cache health check.
2561           *
2562           * @since 6.1.0
2563           *
2564           * @param string $action_url Learn more link for persistent object cache health check.
2565           */
2566          $action_url = apply_filters(
2567              'site_status_persistent_object_cache_url',
2568              /* translators: Localized Support reference. */
2569              __( 'https://developer.wordpress.org/advanced-administration/performance/optimization/#object-caching' )
2570          );
2571  
2572          $result = array(
2573              'test'        => 'persistent_object_cache',
2574              'status'      => 'good',
2575              'badge'       => array(
2576                  'label' => __( 'Performance' ),
2577                  'color' => 'blue',
2578              ),
2579              'label'       => __( 'A persistent object cache is being used' ),
2580              'description' => sprintf(
2581                  '<p>%s</p>',
2582                  __( 'A persistent object cache makes your site&#8217;s database more efficient, resulting in faster load times because WordPress can retrieve your site&#8217;s content and settings much more quickly.' )
2583              ),
2584              'actions'     => sprintf(
2585                  '<p><a href="%s" target="_blank">%s<span class="screen-reader-text"> %s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
2586                  esc_url( $action_url ),
2587                  __( 'Learn more about persistent object caching.' ),
2588                  /* translators: Hidden accessibility text. */
2589                  __( '(opens in a new tab)' )
2590              ),
2591          );
2592  
2593          if ( wp_using_ext_object_cache() ) {
2594              return $result;
2595          }
2596  
2597          if ( ! $this->should_suggest_persistent_object_cache() ) {
2598              $result['label'] = __( 'A persistent object cache is not required' );
2599  
2600              return $result;
2601          }
2602  
2603          $available_services = $this->available_object_cache_services();
2604  
2605          $notes = __( 'Your hosting provider can tell you if a persistent object cache can be enabled on your site.' );
2606  
2607          if ( ! empty( $available_services ) ) {
2608              $notes .= ' ' . sprintf(
2609                  /* translators: Available object caching services. */
2610                  __( 'Your host appears to support the following object caching services: %s.' ),
2611                  implode( ', ', $available_services )
2612              );
2613          }
2614  
2615          /**
2616           * Filters the second paragraph of the health check's description
2617           * when suggesting the use of a persistent object cache.
2618           *
2619           * Hosts may want to replace the notes to recommend their preferred object caching solution.
2620           *
2621           * Plugin authors may want to append notes (not replace) on why object caching is recommended for their plugin.
2622           *
2623           * @since 6.1.0
2624           *
2625           * @param string   $notes              The notes appended to the health check description.
2626           * @param string[] $available_services The list of available persistent object cache services.
2627           */
2628          $notes = apply_filters( 'site_status_persistent_object_cache_notes', $notes, $available_services );
2629  
2630          $result['status']       = 'recommended';
2631          $result['label']        = __( 'You should use a persistent object cache' );
2632          $result['description'] .= sprintf(
2633              '<p>%s</p>',
2634              wp_kses(
2635                  $notes,
2636                  array(
2637                      'a'      => array( 'href' => true ),
2638                      'code'   => true,
2639                      'em'     => true,
2640                      'strong' => true,
2641                  )
2642              )
2643          );
2644  
2645          return $result;
2646      }
2647  
2648      /**
2649       * Calculates total amount of autoloaded data.
2650       *
2651       * @since 6.6.0
2652       *
2653       * @return int Autoloaded data in bytes.
2654       */
2655  	public function get_autoloaded_options_size() {
2656          $alloptions = wp_load_alloptions();
2657  
2658          $total_length = 0;
2659  
2660          foreach ( $alloptions as $option_value ) {
2661              if ( is_array( $option_value ) || is_object( $option_value ) ) {
2662                  $option_value = maybe_serialize( $option_value );
2663              }
2664              $total_length += strlen( (string) $option_value );
2665          }
2666  
2667          return $total_length;
2668      }
2669  
2670      /**
2671       * Tests the number of autoloaded options.
2672       *
2673       * @since 6.6.0
2674       *
2675       * @return array The test results.
2676       */
2677  	public function get_test_autoloaded_options() {
2678          $autoloaded_options_size  = $this->get_autoloaded_options_size();
2679          $autoloaded_options_count = count( wp_load_alloptions() );
2680  
2681          $base_description = __( 'Autoloaded options are configuration settings for plugins and themes that are automatically loaded with every page load in WordPress. Having too many autoloaded options can slow down your site.' );
2682  
2683          $result = array(
2684              'label'       => __( 'Autoloaded options are acceptable' ),
2685              'status'      => 'good',
2686              'badge'       => array(
2687                  'label' => __( 'Performance' ),
2688                  'color' => 'blue',
2689              ),
2690              'description' => sprintf(
2691                  /* translators: 1: Number of autoloaded options, 2: Autoloaded options size. */
2692                  '<p>' . esc_html( $base_description ) . ' ' . __( 'Your site has %1$s autoloaded options (size: %2$s) in the options table, which is acceptable.' ) . '</p>',
2693                  $autoloaded_options_count,
2694                  size_format( $autoloaded_options_size )
2695              ),
2696              'actions'     => '',
2697              'test'        => 'autoloaded_options',
2698          );
2699  
2700          /**
2701           * Filters max bytes threshold to trigger warning in Site Health.
2702           *
2703           * @since 6.6.0
2704           *
2705           * @param int $limit Autoloaded options threshold size. Default 800000.
2706           */
2707          $limit = apply_filters( 'site_status_autoloaded_options_size_limit', 800000 );
2708  
2709          if ( $autoloaded_options_size < $limit ) {
2710              return $result;
2711          }
2712  
2713          $result['status']      = 'critical';
2714          $result['label']       = __( 'Autoloaded options could affect performance' );
2715          $result['description'] = sprintf(
2716              /* translators: 1: Number of autoloaded options, 2: Autoloaded options size. */
2717              '<p>' . esc_html( $base_description ) . ' ' . __( 'Your site has %1$s autoloaded options (size: %2$s) in the options table, which could cause your site to be slow. You can review the options being autoloaded in your database and remove any options that are no longer needed by your site.' ) . '</p>',
2718              $autoloaded_options_count,
2719              size_format( $autoloaded_options_size )
2720          );
2721  
2722          /**
2723           * Filters description to be shown on Site Health warning when threshold is met.
2724           *
2725           * @since 6.6.0
2726           *
2727           * @param string $description Description message when autoloaded options bigger than threshold.
2728           */
2729          $result['description'] = apply_filters( 'site_status_autoloaded_options_limit_description', $result['description'] );
2730  
2731          $result['actions'] = sprintf(
2732              /* translators: 1: HelpHub URL, 2: Link description. */
2733              '<p><a target="_blank" href="%1$s">%2$s</a></p>',
2734              esc_url( __( 'https://developer.wordpress.org/advanced-administration/performance/optimization/#autoloaded-options' ) ),
2735              __( 'More info about optimizing autoloaded options' )
2736          );
2737  
2738          /**
2739           * Filters actionable information to tackle the problem. It can be a link to an external guide.
2740           *
2741           * @since 6.6.0
2742           *
2743           * @param string $actions Call to Action to be used to point to the right direction to solve the issue.
2744           */
2745          $result['actions'] = apply_filters( 'site_status_autoloaded_options_action_to_perform', $result['actions'] );
2746          return $result;
2747      }
2748  
2749      /**
2750       * Tests whether search engine indexing is enabled.
2751       *
2752       * Surfaces as “good” if `blog_public === 1`, or “recommended” if `blog_public === 0`.
2753       *
2754       * @since 6.9.0
2755       *
2756       * @return array The test results.
2757       */
2758  	public function get_test_search_engine_visibility() {
2759          $result = array(
2760              'label'       => __( 'Search engine indexing is enabled.' ),
2761              'status'      => 'good',
2762              'badge'       => array(
2763                  'label' => __( 'Privacy' ),
2764                  'color' => 'blue',
2765              ),
2766              'description' => sprintf(
2767                  '<p>%s</p>',
2768                  __( 'Search engines can crawl and index your site. No action needed.' )
2769              ),
2770              'actions'     => sprintf(
2771                  '<p><a href="%1$s">%2$s</a></p>',
2772                  esc_url( admin_url( 'options-reading.php#blog_public' ) ),
2773                  __( 'Review your visibility settings' )
2774              ),
2775              'test'        => 'search_engine_visibility',
2776          );
2777  
2778          // If indexing is discouraged, flip to “recommended”:
2779          if ( ! get_option( 'blog_public' ) ) {
2780              $result['status']         = 'recommended';
2781              $result['label']          = __( 'Search engines are discouraged from indexing this site.' );
2782              $result['badge']['color'] = 'blue';
2783              $result['description']    = sprintf(
2784                  '<p>%s</p>',
2785                  __( 'Your site is hidden from search engines. Consider enabling indexing if this is a public site.' )
2786              );
2787          }
2788  
2789          return $result;
2790      }
2791  
2792      /**
2793       * Tests if opcode cache is enabled and available.
2794       *
2795       * @since 7.0.0
2796       *
2797       * @return array<string, string|array<string, string>> The test result.
2798       */
2799  	public function get_test_opcode_cache(): array {
2800          $opcode_cache_enabled = false;
2801          if ( function_exists( 'opcache_get_status' ) ) {
2802              $status = @opcache_get_status( false ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Warning emitted in failure case.
2803              if ( $status && true === $status['opcache_enabled'] ) {
2804                  $opcode_cache_enabled = true;
2805              }
2806          }
2807  
2808          $result = array(
2809              'label'       => __( 'Opcode cache is enabled' ),
2810              'status'      => 'good',
2811              'badge'       => array(
2812                  'label' => __( 'Performance' ),
2813                  'color' => 'blue',
2814              ),
2815              'description' => sprintf(
2816                  '<p>%s</p>',
2817                  __( 'Opcode cache improves PHP performance by storing precompiled script bytecode in memory, reducing the need for PHP to load and parse scripts on each request.' )
2818              ),
2819              'actions'     => sprintf(
2820                  '<p><a href="%s" target="_blank">%s<span class="screen-reader-text"> %s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
2821                  esc_url( 'https://www.php.net/manual/en/book.opcache.php' ),
2822                  __( 'Learn more about OPcache.' ),
2823                  /* translators: Hidden accessibility text. */
2824                  __( '(opens in a new tab)' )
2825              ),
2826              'test'        => 'opcode_cache',
2827          );
2828  
2829          if ( ! $opcode_cache_enabled ) {
2830              $result['status']       = 'recommended';
2831              $result['label']        = __( 'Opcode cache is not enabled' );
2832              $result['description'] .= '<p>' . __( 'Enabling this cache can significantly improve the performance of your site.' ) . '</p>';
2833          }
2834  
2835          return $result;
2836      }
2837  
2838      /**
2839       * Tests whether the Secrets API has a usable key.
2840       *
2841       * There is no settings screen for secrets, so this is how an administrator notices
2842       * a missing or broken key, or a key that no longer unlocks the stored secrets.
2843       *
2844       * @since 7.2.0
2845       *
2846       * @return array The test result.
2847       *
2848       * @phpstan-return array{label: string, status: 'good'|'recommended'|'critical', badge: array{label: string, color: string}, description: string, actions: string, test: string}
2849       */
2850  	public function get_test_secrets_api_key_source(): array {
2851          $provider = _wp_secrets_get_provider();
2852  
2853          if ( ! $this->secrets_api_uses_keyring( $provider ) ) {
2854              return $this->get_secrets_api_test_result(
2855                  'secrets_api_key_source',
2856                  __( 'Secrets API keys are managed by the provider' ),
2857                  'good',
2858                  sprintf(
2859                      '<p>%s</p>',
2860                      sprintf(
2861                          /* translators: 1: secrets.php, 2: Name of the active secrets provider, 3: WP_SECRETS_KEY */
2862                          __( 'Secrets are protected by the provider of the %1$s drop-in: %2$s. %3$s is not used.' ),
2863                          '<code>secrets.php</code>',
2864                          esc_html( $provider->get_label() ),
2865                          '<code>WP_SECRETS_KEY</code>'
2866                      )
2867                  )
2868              );
2869          }
2870  
2871          $keyring    = _wp_secrets_get_key_manager()->get_keyring();
2872          $key_source = $keyring->get_key_source();
2873          $key_status = $keyring instanceof WP_Secrets_Config_Key_Provider ? $keyring->get_key_status() : null;
2874  
2875          // The broken keyring's description is translated, so check its class rather than its text.
2876          if ( $keyring instanceof WP_Secrets_Broken_Keyring ) {
2877              return $this->get_secrets_api_test_result(
2878                  'secrets_api_key_source',
2879                  __( 'Secrets API key source is broken' ),
2880                  'critical',
2881                  sprintf(
2882                      '<p>%s</p>',
2883                      esc_html__( 'The active keyring did not load correctly. No secret can be encrypted or decrypted until this is fixed.' )
2884                  )
2885              );
2886          }
2887  
2888          /*
2889           * Once a root key exists, it is wrapped with the current site key, and core has no way
2890           * to re-wrap it under another one. Changing the key source then locks every stored
2891           * secret, and blocks saving new ones, until the change is reverted.
2892           */
2893          $has_root_key = false !== get_site_option( WP_Secrets_Key_Manager::ROOT_KEY_OPTION );
2894  
2895          if ( $has_root_key ) {
2896              $root_key = _wp_secrets_get_key_manager()->get_root_key();
2897  
2898              if ( is_wp_error( $root_key ) ) {
2899                  /*
2900                   * Only the default keyring reads wp-config.php. A keyring from a secrets.php
2901                   * drop-in fails for its own reasons, such as an unreachable key service, and
2902                   * its error is the useful part.
2903                   */
2904                  $cause = $keyring instanceof WP_Secrets_Config_Key_Provider
2905                      ? sprintf(
2906                          /* translators: %s: WP_SECRETS_KEY */
2907                          __( 'This happens when %s was changed or removed after secrets were stored. Restoring the previous value fixes it.' ),
2908                          '<code>WP_SECRETS_KEY</code>'
2909                      )
2910                      : sprintf(
2911                          /* translators: 1: secrets.php, 2: Error message from the keyring. */
2912                          __( 'The keyring of the %1$s drop-in reported: %2$s' ),
2913                          '<code>secrets.php</code>',
2914                          esc_html( $root_key->get_error_message() )
2915                      );
2916  
2917                  return $this->get_secrets_api_test_result(
2918                      'secrets_api_key_source',
2919                      __( 'Secrets API cannot unlock the stored secrets' ),
2920                      'critical',
2921                      sprintf(
2922                          '<p>%s</p><p>%s</p>',
2923                          esc_html__( 'The configured key cannot decrypt the root key that protects the stored secrets, so no secret can be read or saved.' ),
2924                          $cause
2925                      )
2926                  );
2927              }
2928  
2929              wp_secrets_memzero( $root_key );
2930          }
2931  
2932          if ( WP_Secrets_Config_Key_Provider::KEY_STATUS_LEGACY === $key_status ) {
2933              return $this->get_secrets_api_test_result(
2934                  'secrets_api_key_source',
2935                  __( 'Secrets API key is not in the recommended form' ),
2936                  'recommended',
2937                  sprintf(
2938                      '<p>%s</p>',
2939                      $has_root_key
2940                          ? sprintf(
2941                              /* translators: %s: WP_SECRETS_KEY */
2942                              __( '%s is defined, but not as a base64-encoded random 32-byte value. Keep its current value: secrets are already encrypted with it, and changing it makes them unreadable.' ),
2943                              '<code>WP_SECRETS_KEY</code>'
2944                          )
2945                          : sprintf(
2946                              /* translators: %s: WP_SECRETS_KEY */
2947                              __( '%s is defined, but not as a base64-encoded random 32-byte value. No secrets are stored yet, so it can still be replaced with such a value.' ),
2948                              '<code>WP_SECRETS_KEY</code>'
2949                          )
2950                  )
2951              );
2952          }
2953  
2954          if ( WP_Secrets_Config_Key_Provider::KEY_STATUS_UNDEFINED === $key_status || WP_Secrets_Config_Key_Provider::KEY_STATUS_UNUSABLE === $key_status ) {
2955              $is_defined = WP_Secrets_Config_Key_Provider::KEY_STATUS_UNUSABLE === $key_status;
2956              $example    = sprintf( "define( 'WP_SECRETS_KEY', '%s' );", base64_encode( random_bytes( 32 ) ) );
2957  
2958              return $this->get_secrets_api_test_result(
2959                  'secrets_api_key_source',
2960                  __( 'Secrets API has no encryption key' ),
2961                  'recommended',
2962                  sprintf(
2963                      '<p>%s</p><p>%s</p><p><code>%s</code></p><p>%s</p>',
2964                      $is_defined
2965                          ? sprintf(
2966                              /* translators: 1: WP_SECRETS_KEY, 2: wp-config.php, 3: wp-config-sample.php */
2967                              __( '%1$s is defined in %2$s, but its value cannot be used: it is empty, still the placeholder from %3$s, or the same as one of the authentication keys and salts. Plugins cannot store API keys and other credentials with the Secrets API until it is fixed.' ),
2968                              '<code>WP_SECRETS_KEY</code>',
2969                              '<code>wp-config.php</code>',
2970                              '<code>wp-config-sample.php</code>'
2971                          )
2972                          : sprintf(
2973                              /* translators: 1: WP_SECRETS_KEY, 2: wp-config.php */
2974                              __( '%1$s is not defined in %2$s. Plugins cannot store API keys and other credentials with the Secrets API until it is.' ),
2975                              '<code>WP_SECRETS_KEY</code>',
2976                              '<code>wp-config.php</code>'
2977                          ),
2978                      $is_defined
2979                          ? sprintf(
2980                              /* translators: 1: WP_SECRETS_KEY, 2: wp-config.php */
2981                              __( 'Replace the %1$s line in %2$s with this one:' ),
2982                              '<code>WP_SECRETS_KEY</code>',
2983                              '<code>wp-config.php</code>'
2984                          )
2985                          : sprintf(
2986                              /* translators: 1: wp-config.php, 2: Translated version of "That's all, stop editing! Happy publishing." */
2987                              __( 'Add this line to %1$s, above the line reading %2$s:' ),
2988                              '<code>wp-config.php</code>',
2989                              '<code>/* ' . __( 'That&#8217;s all, stop editing! Happy publishing.' ) . ' */</code>'
2990                          ),
2991                      esc_html( $example ),
2992                      esc_html__( 'A new value is generated each time this page loads. Keep a copy of the one you use with your backups: secrets stored with it cannot be read without it.' )
2993                  )
2994              );
2995          }
2996  
2997          return $this->get_secrets_api_test_result(
2998              'secrets_api_key_source',
2999              __( 'Secrets API is using a dedicated key' ),
3000              'good',
3001              sprintf( '<p>%s</p>', esc_html( $key_source ) )
3002          );
3003      }
3004  
3005      /**
3006       * Tests whether every stored secret still decrypts.
3007       *
3008       * Network secrets are included only for a super admin on a multisite install –
3009       * never shown to a site administrator who is not one.
3010       *
3011       * @since 7.2.0
3012       *
3013       * @return array The test result.
3014       *
3015       * @phpstan-return array{label: string, status: 'good'|'recommended'|'critical', badge: array{label: string, color: string}, description: string, actions: string, test: string}
3016       */
3017  	public function get_test_secrets_api_undecryptable(): array {
3018          $broken = $this->get_undecryptable_secrets( false );
3019  
3020          if ( ! is_wp_error( $broken ) && is_multisite() && is_super_admin() ) {
3021              $network_broken = $this->get_undecryptable_secrets( true );
3022              $broken         = is_wp_error( $network_broken ) ? $network_broken : array_merge( $broken, $network_broken );
3023          }
3024  
3025          // Secrets that cannot be listed cannot be checked, which must not read as all of them decrypting.
3026          if ( is_wp_error( $broken ) ) {
3027              return $this->get_secrets_api_test_result(
3028                  'secrets_api_undecryptable',
3029                  __( 'Secrets could not be checked' ),
3030                  'critical',
3031                  sprintf(
3032                      '<p>%s</p><p>%s</p>',
3033                      esc_html__( 'The stored secrets could not be listed, so none of them could be checked. Secrets probably cannot be read or written either until this is fixed.' ),
3034                      esc_html( $broken->get_error_message() )
3035                  )
3036              );
3037          }
3038  
3039          if ( empty( $broken ) ) {
3040              return $this->get_secrets_api_test_result(
3041                  'secrets_api_undecryptable',
3042                  __( 'All secrets can be decrypted' ),
3043                  'good',
3044                  sprintf( '<p>%s</p>', esc_html__( 'Every stored secret decrypted successfully.' ) )
3045              );
3046          }
3047  
3048          $items = '';
3049  
3050          foreach ( $broken as $entry ) {
3051              $items .= sprintf(
3052                  '<li>%s (%s)</li>',
3053                  esc_html( $entry['name'] ),
3054                  sprintf(
3055                      /* translators: %s: A secret's last known fingerprint. */
3056                      esc_html__( 'fingerprint: %s' ),
3057                      esc_html( $entry['fingerprint'] )
3058                  )
3059              );
3060          }
3061  
3062          return $this->get_secrets_api_test_result(
3063              'secrets_api_undecryptable',
3064              __( 'Some secrets cannot be decrypted' ),
3065              'critical',
3066              sprintf(
3067                  '<p>%s</p><ul>%s</ul><p>%s</p>',
3068                  esc_html__( 'The following secrets exist but could not be decrypted with the current key.' ),
3069                  $items,
3070                  sprintf(
3071                      /* translators: %s: WP_SECRETS_KEY */
3072                      __( 'This can happen after %s was changed or removed, after restoring a database backup without its matching key, or after a failed key rotation. Restoring the previous key makes the secrets readable again. Otherwise, each credential must be entered again.' ),
3073                      '<code>WP_SECRETS_KEY</code>'
3074                  )
3075              )
3076          );
3077      }
3078  
3079      /**
3080       * Tests whether any secrets are flagged as needing rotation.
3081       *
3082       * @since 7.2.0
3083       *
3084       * @return array The test result.
3085       *
3086       * @phpstan-return array{label: string, status: 'good'|'recommended'|'critical', badge: array{label: string, color: string}, description: string, actions: string, test: string}
3087       */
3088  	public function get_test_secrets_api_needs_rotation(): array {
3089          $count = $this->count_secrets_needing_rotation( false );
3090  
3091          if ( ! is_wp_error( $count ) && is_multisite() && is_super_admin() ) {
3092              $network_count = $this->count_secrets_needing_rotation( true );
3093              $count         = is_wp_error( $network_count ) ? $network_count : $count + $network_count;
3094          }
3095  
3096          if ( is_wp_error( $count ) ) {
3097              return $this->get_secrets_api_test_result(
3098                  'secrets_api_needs_rotation',
3099                  __( 'Secrets could not be checked for pending rotation' ),
3100                  'recommended',
3101                  sprintf( '<p>%s</p>', esc_html( $count->get_error_message() ) )
3102              );
3103          }
3104  
3105          if ( 0 === $count ) {
3106              return $this->get_secrets_api_test_result(
3107                  'secrets_api_needs_rotation',
3108                  __( 'No secrets are pending rotation' ),
3109                  'good',
3110                  sprintf( '<p>%s</p>', esc_html__( 'No secret is flagged as needing rotation.' ) )
3111              );
3112          }
3113  
3114          return $this->get_secrets_api_test_result(
3115              'secrets_api_needs_rotation',
3116              __( 'Some secrets are pending rotation' ),
3117              'recommended',
3118              sprintf(
3119                  '<p>%s</p>',
3120                  esc_html(
3121                      sprintf(
3122                          /* translators: %d: Number of secrets flagged for rotation. */
3123                          _n(
3124                              '%d secret was imported from an existing option and is flagged for rotation. A credential that sat in a plain option has already been through whatever backups and replication paths that option went through; re-entering it with a new value is recommended.',
3125                              '%d secrets were imported from existing options and are flagged for rotation. A credential that sat in a plain option has already been through whatever backups and replication paths that option went through; re-entering each with a new value is recommended.',
3126                              $count
3127                          ),
3128                          $count
3129                      )
3130                  )
3131              )
3132          );
3133      }
3134  
3135      /**
3136       * Builds the result of a Secrets API test.
3137       *
3138       * @since 7.2.0
3139       *
3140       * @param string $test        The test's identifier, as registered in get_tests().
3141       * @param string $label       Short label for the test result.
3142       * @param string $status      One of 'good', 'recommended', 'critical'.
3143       * @param string $description HTML description, normally one or more <p> elements.
3144       * @return array The test result.
3145       *
3146       * @phpstan-param 'good'|'recommended'|'critical' $status
3147       * @phpstan-return array{label: string, status: 'good'|'recommended'|'critical', badge: array{label: string, color: string}, description: string, actions: string, test: string}
3148       */
3149  	private function get_secrets_api_test_result( string $test, string $label, string $status, string $description ): array {
3150          return array(
3151              'label'       => $label,
3152              'status'      => $status,
3153              'badge'       => array(
3154                  'label' => __( 'Security' ),
3155                  'color' => 'blue',
3156              ),
3157              'description' => $description,
3158              'actions'     => '',
3159              'test'        => $test,
3160          );
3161      }
3162  
3163      /**
3164       * Determines whether the active secrets provider protects secrets with the keyring.
3165       *
3166       * A secrets.php drop-in can replace the whole provider, which then protects secrets
3167       * with its own keys. The default keyring, and WP_SECRETS_KEY, are not used at all.
3168       *
3169       * @since 7.2.0
3170       *
3171       * @param WP_Secrets_Provider $provider The active provider.
3172       * @return bool
3173       */
3174  	private function secrets_api_uses_keyring( WP_Secrets_Provider $provider ): bool {
3175          return $provider instanceof WP_Secrets_Libsodium_Provider || $provider instanceof WP_Secrets_Broken_Provider;
3176      }
3177  
3178      /**
3179       * Finds the stored secrets that fail to decrypt, for one scope.
3180       *
3181       * @since 7.2.0
3182       *
3183       * @param bool $network Whether to check network-scope secrets.
3184       * @return array|WP_Error List of array( 'name' => ..., 'fingerprint' => ... ),
3185       *                        or WP_Error when the secrets cannot be listed.
3186       *
3187       * @phpstan-return list<array{name: string, fingerprint: string}>|WP_Error
3188       */
3189  	private function get_undecryptable_secrets( bool $network ) {
3190          $entries = $network ? wp_list_network_secrets() : wp_list_secrets();
3191  
3192          if ( is_wp_error( $entries ) ) {
3193              return $entries;
3194          }
3195  
3196          $broken = array();
3197  
3198          foreach ( $entries as $entry ) {
3199              $secret = $network ? wp_get_network_secret( $entry['name'] ) : wp_get_secret( $entry['name'] );
3200  
3201              if ( is_wp_error( $secret ) ) {
3202                  $broken[] = array(
3203                      'name'        => $entry['name'],
3204                      'fingerprint' => $entry['fingerprint'],
3205                  );
3206              }
3207          }
3208  
3209          return $broken;
3210      }
3211  
3212      /**
3213       * Counts the stored secrets flagged as needing rotation, for one scope.
3214       *
3215       * @since 7.2.0
3216       *
3217       * @param bool $network Whether to check network-scope secrets.
3218       * @return int|WP_Error The number of secrets, or WP_Error when the secrets cannot be listed.
3219       *
3220       * @phpstan-return int<0, max>|WP_Error
3221       */
3222  	private function count_secrets_needing_rotation( bool $network ) {
3223          $entries = $network ? wp_list_network_secrets() : wp_list_secrets();
3224  
3225          if ( is_wp_error( $entries ) ) {
3226              return $entries;
3227          }
3228  
3229          $count = 0;
3230  
3231          foreach ( $entries as $entry ) {
3232              if ( ! empty( $entry['needs_rotation'] ) ) {
3233                  ++$count;
3234              }
3235          }
3236  
3237          return $count;
3238      }
3239  
3240      /**
3241       * Returns a set of tests that belong to the site status page.
3242       *
3243       * Each site status test is defined here, they may be `direct` tests, that run on page load, or `async` tests
3244       * which will run later down the line via JavaScript calls to improve page performance and hopefully also user
3245       * experiences.
3246       *
3247       * @since 5.2.0
3248       * @since 5.6.0 Added support for `has_rest` and `permissions`.
3249       *
3250       * @return array The list of tests to run.
3251       */
3252  	public static function get_tests() {
3253          $tests = array(
3254              'direct' => array(
3255                  'wordpress_version'            => array(
3256                      'label' => __( 'WordPress Version' ),
3257                      'test'  => 'wordpress_version',
3258                  ),
3259                  'plugin_version'               => array(
3260                      'label' => __( 'Plugin Versions' ),
3261                      'test'  => 'plugin_version',
3262                  ),
3263                  'theme_version'                => array(
3264                      'label' => __( 'Theme Versions' ),
3265                      'test'  => 'theme_version',
3266                  ),
3267                  'php_version'                  => array(
3268                      'label' => __( 'PHP Version' ),
3269                      'test'  => 'php_version',
3270                  ),
3271                  'php_extensions'               => array(
3272                      'label' => __( 'PHP Extensions' ),
3273                      'test'  => 'php_extensions',
3274                  ),
3275                  'php_default_timezone'         => array(
3276                      'label' => __( 'PHP Default Timezone' ),
3277                      'test'  => 'php_default_timezone',
3278                  ),
3279                  'php_sessions'                 => array(
3280                      'label' => __( 'PHP Sessions' ),
3281                      'test'  => 'php_sessions',
3282                  ),
3283                  'sql_server'                   => array(
3284                      'label' => __( 'Database Server version' ),
3285                      'test'  => 'sql_server',
3286                  ),
3287                  'ssl_support'                  => array(
3288                      'label' => __( 'Secure communication' ),
3289                      'test'  => 'ssl_support',
3290                  ),
3291                  'scheduled_events'             => array(
3292                      'label' => __( 'Scheduled events' ),
3293                      'test'  => 'scheduled_events',
3294                  ),
3295                  'http_requests'                => array(
3296                      'label' => __( 'HTTP Requests' ),
3297                      'test'  => 'http_requests',
3298                  ),
3299                  'rest_availability'            => array(
3300                      'label'     => __( 'REST API availability' ),
3301                      'test'      => 'rest_availability',
3302                      'skip_cron' => true,
3303                  ),
3304                  'debug_enabled'                => array(
3305                      'label' => __( 'Debugging enabled' ),
3306                      'test'  => 'is_in_debug_mode',
3307                  ),
3308                  'file_uploads'                 => array(
3309                      'label' => __( 'File uploads' ),
3310                      'test'  => 'file_uploads',
3311                  ),
3312                  'plugin_theme_auto_updates'    => array(
3313                      'label' => __( 'Plugin and theme auto-updates' ),
3314                      'test'  => 'plugin_theme_auto_updates',
3315                  ),
3316                  'update_temp_backup_writable'  => array(
3317                      'label' => __( 'Plugin and theme temporary backup directory access' ),
3318                      'test'  => 'update_temp_backup_writable',
3319                  ),
3320                  'available_updates_disk_space' => array(
3321                      'label' => __( 'Available disk space' ),
3322                      'test'  => 'available_updates_disk_space',
3323                  ),
3324                  'autoloaded_options'           => array(
3325                      'label' => __( 'Autoloaded options' ),
3326                      'test'  => 'autoloaded_options',
3327                  ),
3328                  'insecure_registration'        => array(
3329                      'label' => __( 'Open Registration with privileged default role' ),
3330                      'test'  => 'insecure_registration',
3331                  ),
3332                  'search_engine_visibility'     => array(
3333                      'label' => __( 'Search Engine Visibility' ),
3334                      'test'  => 'search_engine_visibility',
3335                  ),
3336                  'opcode_cache'                 => array(
3337                      'label' => __( 'Opcode cache' ),
3338                      'test'  => 'opcode_cache',
3339                  ),
3340                  'secrets_api_key_source'       => array(
3341                      'label' => __( 'Secrets API key source' ),
3342                      'test'  => 'secrets_api_key_source',
3343                  ),
3344                  'secrets_api_undecryptable'    => array(
3345                      'label' => __( 'Secrets API: undecryptable secrets' ),
3346                      'test'  => 'secrets_api_undecryptable',
3347                  ),
3348                  'secrets_api_needs_rotation'   => array(
3349                      'label' => __( 'Secrets API: credentials pending rotation' ),
3350                      'test'  => 'secrets_api_needs_rotation',
3351                  ),
3352              ),
3353              'async'  => array(
3354                  'dotorg_communication' => array(
3355                      'label'             => __( 'Communication with WordPress.org' ),
3356                      'test'              => rest_url( 'wp-site-health/v1/tests/dotorg-communication' ),
3357                      'has_rest'          => true,
3358                      'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_dotorg_communication' ),
3359                  ),
3360                  'background_updates'   => array(
3361                      'label'             => __( 'Background updates' ),
3362                      'test'              => rest_url( 'wp-site-health/v1/tests/background-updates' ),
3363                      'has_rest'          => true,
3364                      'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_background_updates' ),
3365                  ),
3366                  'loopback_requests'    => array(
3367                      'label'             => __( 'Loopback request' ),
3368                      'test'              => rest_url( 'wp-site-health/v1/tests/loopback-requests' ),
3369                      'has_rest'          => true,
3370                      'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_loopback_requests' ),
3371                  ),
3372                  'https_status'         => array(
3373                      'label'             => __( 'HTTPS status' ),
3374                      'test'              => rest_url( 'wp-site-health/v1/tests/https-status' ),
3375                      'has_rest'          => true,
3376                      'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_https_status' ),
3377                  ),
3378              ),
3379          );
3380  
3381          // Conditionally include Authorization header test if the site isn't protected by Basic Auth.
3382          if ( ! wp_is_site_protected_by_basic_auth() ) {
3383              $tests['async']['authorization_header'] = array(
3384                  'label'     => __( 'Authorization header' ),
3385                  'test'      => rest_url( 'wp-site-health/v1/tests/authorization-header' ),
3386                  'has_rest'  => true,
3387                  'headers'   => array( 'Authorization' => 'Basic ' . base64_encode( 'user:pwd' ) ),
3388                  'skip_cron' => true,
3389              );
3390          }
3391  
3392          // Only check for caches in production environments.
3393          if ( 'production' === wp_get_environment_type() ) {
3394              $tests['async']['page_cache'] = array(
3395                  'label'             => __( 'Page cache' ),
3396                  'test'              => rest_url( 'wp-site-health/v1/tests/page-cache' ),
3397                  'has_rest'          => true,
3398                  'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_page_cache' ),
3399              );
3400  
3401              $tests['direct']['persistent_object_cache'] = array(
3402                  'label' => __( 'Persistent object cache' ),
3403                  'test'  => 'persistent_object_cache',
3404              );
3405          }
3406  
3407          /**
3408           * Filters which site status tests are run on a site.
3409           *
3410           * The site health is determined by a set of tests based on best practices from
3411           * both the WordPress Hosting Team and web standards in general.
3412           *
3413           * Some sites may not have the same requirements, for example the automatic update
3414           * checks may be handled by a host, and are therefore disabled in core.
3415           * Or maybe you want to introduce a new test, is caching enabled/disabled/stale for example.
3416           *
3417           * Tests may be added either as direct, or asynchronous ones. Any test that may require some time
3418           * to complete should run asynchronously, to avoid extended loading periods within wp-admin.
3419           *
3420           * @since 5.2.0
3421           * @since 5.6.0 Added the `async_direct_test` array key for asynchronous tests.
3422           *              Added the `skip_cron` array key for all tests.
3423           *
3424           * @param array[] $tests {
3425           *     An associative array of direct and asynchronous tests.
3426           *
3427           *     @type array[] $direct {
3428           *         An array of direct tests.
3429           *
3430           *         @type array ...$identifier {
3431           *             `$identifier` should be a unique identifier for the test. Plugins and themes are encouraged to
3432           *             prefix test identifiers with their slug to avoid collisions between tests.
3433           *
3434           *             @type string   $label     The friendly label to identify the test.
3435           *             @type callable $test      The callback function that runs the test and returns its result.
3436           *             @type bool     $skip_cron Whether to skip this test when running as cron.
3437           *         }
3438           *     }
3439           *     @type array[] $async {
3440           *         An array of asynchronous tests.
3441           *
3442           *         @type array ...$identifier {
3443           *             `$identifier` should be a unique identifier for the test. Plugins and themes are encouraged to
3444           *             prefix test identifiers with their slug to avoid collisions between tests.
3445           *
3446           *             @type string   $label             The friendly label to identify the test.
3447           *             @type string   $test              An admin-ajax.php action to be called to perform the test, or
3448           *                                               if `$has_rest` is true, a URL to a REST API endpoint to perform
3449           *                                               the test.
3450           *             @type bool     $has_rest          Whether the `$test` property points to a REST API endpoint.
3451           *             @type bool     $skip_cron         Whether to skip this test when running as cron.
3452           *             @type callable $async_direct_test A manner of directly calling the test marked as asynchronous,
3453           *                                               as the scheduled event can not authenticate, and endpoints
3454           *                                               may require authentication.
3455           *         }
3456           *     }
3457           * }
3458           */
3459          $tests = apply_filters( 'site_status_tests', $tests );
3460  
3461          // Ensure that the filtered tests contain the required array keys.
3462          $tests = array_merge(
3463              array(
3464                  'direct' => array(),
3465                  'async'  => array(),
3466              ),
3467              $tests
3468          );
3469  
3470          return $tests;
3471      }
3472  
3473      /**
3474       * Adds a class to the body HTML tag.
3475       *
3476       * Filters the body class string for admin pages and adds our own class for easier styling.
3477       *
3478       * @since 5.2.0
3479       *
3480       * @param string $body_class The body class string.
3481       * @return string The modified body class string.
3482       */
3483  	public function admin_body_class( $body_class ) {
3484          $screen = get_current_screen();
3485          if ( 'site-health' !== $screen->id ) {
3486              return $body_class;
3487          }
3488  
3489          $body_class .= ' site-health';
3490  
3491          return $body_class;
3492      }
3493  
3494      /**
3495       * Initiates the WP_Cron schedule test cases.
3496       *
3497       * @since 5.2.0
3498       */
3499  	private function wp_schedule_test_init() {
3500          $this->schedules = wp_get_schedules();
3501          $this->get_cron_tasks();
3502      }
3503  
3504      /**
3505       * Populates the list of cron events and store them to a class-wide variable.
3506       *
3507       * @since 5.2.0
3508       */
3509  	private function get_cron_tasks() {
3510          $cron_tasks = _get_cron_array();
3511  
3512          if ( empty( $cron_tasks ) ) {
3513              $this->crons = new WP_Error( 'no_tasks', __( 'No scheduled events exist on this site.' ) );
3514              return;
3515          }
3516  
3517          $this->crons = array();
3518  
3519          foreach ( $cron_tasks as $time => $cron ) {
3520              foreach ( $cron as $hook => $dings ) {
3521                  foreach ( $dings as $sig => $data ) {
3522  
3523                      $this->crons[ "$hook-$sig-$time" ] = (object) array(
3524                          'hook'     => $hook,
3525                          'time'     => $time,
3526                          'sig'      => $sig,
3527                          'args'     => $data['args'],
3528                          'schedule' => $data['schedule'],
3529                          'interval' => $data['interval'] ?? null,
3530                      );
3531  
3532                  }
3533              }
3534          }
3535      }
3536  
3537      /**
3538       * Checks if any scheduled tasks have been missed.
3539       *
3540       * Returns a boolean value of `true` if a scheduled task has been missed and ends processing.
3541       *
3542       * If the list of crons is an instance of WP_Error, returns the instance instead of a boolean value.
3543       *
3544       * @since 5.2.0
3545       *
3546       * @return bool|WP_Error True if a cron was missed, false if not. WP_Error if the cron is set to that.
3547       */
3548  	public function has_missed_cron() {
3549          if ( is_wp_error( $this->crons ) ) {
3550              return $this->crons;
3551          }
3552  
3553          foreach ( $this->crons as $id => $cron ) {
3554              if ( ( $cron->time - time() ) < $this->timeout_missed_cron ) {
3555                  $this->last_missed_cron = $cron->hook;
3556                  return true;
3557              }
3558          }
3559  
3560          return false;
3561      }
3562  
3563      /**
3564       * Checks if any scheduled tasks are late.
3565       *
3566       * Returns a boolean value of `true` if a scheduled task is late and ends processing.
3567       *
3568       * If the list of crons is an instance of WP_Error, returns the instance instead of a boolean value.
3569       *
3570       * @since 5.3.0
3571       *
3572       * @return bool|WP_Error True if a cron is late, false if not. WP_Error if the cron is set to that.
3573       */
3574  	public function has_late_cron() {
3575          if ( is_wp_error( $this->crons ) ) {
3576              return $this->crons;
3577          }
3578  
3579          foreach ( $this->crons as $id => $cron ) {
3580              $cron_offset = $cron->time - time();
3581              if (
3582                  $cron_offset >= $this->timeout_missed_cron &&
3583                  $cron_offset < $this->timeout_late_cron
3584              ) {
3585                  $this->last_late_cron = $cron->hook;
3586                  return true;
3587              }
3588          }
3589  
3590          return false;
3591      }
3592  
3593      /**
3594       * Checks for potential issues with plugin and theme auto-updates.
3595       *
3596       * Though there is no way to 100% determine if plugin and theme auto-updates are configured
3597       * correctly, a few educated guesses could be made to flag any conditions that would
3598       * potentially cause unexpected behaviors.
3599       *
3600       * @since 5.5.0
3601       *
3602       * @return object The test results.
3603       */
3604  	public function detect_plugin_theme_auto_update_issues() {
3605          $mock_plugin = (object) array(
3606              'id'            => 'w.org/plugins/a-fake-plugin',
3607              'slug'          => 'a-fake-plugin',
3608              'plugin'        => 'a-fake-plugin/a-fake-plugin.php',
3609              'new_version'   => '9.9',
3610              'url'           => 'https://wordpress.org/plugins/a-fake-plugin/',
3611              'package'       => 'https://downloads.wordpress.org/plugin/a-fake-plugin.9.9.zip',
3612              'icons'         => array(
3613                  '2x' => 'https://ps.w.org/a-fake-plugin/assets/icon-256x256.png',
3614                  '1x' => 'https://ps.w.org/a-fake-plugin/assets/icon-128x128.png',
3615              ),
3616              'banners'       => array(
3617                  '2x' => 'https://ps.w.org/a-fake-plugin/assets/banner-1544x500.png',
3618                  '1x' => 'https://ps.w.org/a-fake-plugin/assets/banner-772x250.png',
3619              ),
3620              'banners_rtl'   => array(),
3621              'tested'        => '5.5.0',
3622              'requires_php'  => '5.6.20',
3623              'compatibility' => new stdClass(),
3624          );
3625  
3626          $mock_theme = (object) array(
3627              'theme'        => 'a-fake-theme',
3628              'new_version'  => '9.9',
3629              'url'          => 'https://wordpress.org/themes/a-fake-theme/',
3630              'package'      => 'https://downloads.wordpress.org/theme/a-fake-theme.9.9.zip',
3631              'requires'     => '5.0.0',
3632              'requires_php' => '5.6.20',
3633          );
3634  
3635          $test_plugins_enabled = wp_is_auto_update_forced_for_item( 'plugin', true, $mock_plugin );
3636          $test_themes_enabled  = wp_is_auto_update_forced_for_item( 'theme', true, $mock_theme );
3637  
3638          $ui_enabled_for_plugins = wp_is_auto_update_enabled_for_type( 'plugin' );
3639          $ui_enabled_for_themes  = wp_is_auto_update_enabled_for_type( 'theme' );
3640          $plugin_filter_present  = has_filter( 'auto_update_plugin' );
3641          $theme_filter_present   = has_filter( 'auto_update_theme' );
3642  
3643          if ( ( ! $test_plugins_enabled && $ui_enabled_for_plugins )
3644              || ( ! $test_themes_enabled && $ui_enabled_for_themes )
3645          ) {
3646              return (object) array(
3647                  'status'  => 'critical',
3648                  'message' => __( 'Auto-updates for plugins and/or themes appear to be disabled, but settings are still set to be displayed. This could cause auto-updates to not work as expected.' ),
3649              );
3650          }
3651  
3652          if ( ( ! $test_plugins_enabled && $plugin_filter_present )
3653              && ( ! $test_themes_enabled && $theme_filter_present )
3654          ) {
3655              return (object) array(
3656                  'status'  => 'recommended',
3657                  'message' => __( 'Auto-updates for plugins and themes appear to be disabled. This will prevent your site from receiving new versions automatically when available.' ),
3658              );
3659          } elseif ( ! $test_plugins_enabled && $plugin_filter_present ) {
3660              return (object) array(
3661                  'status'  => 'recommended',
3662                  'message' => __( 'Auto-updates for plugins appear to be disabled. This will prevent your site from receiving new versions automatically when available.' ),
3663              );
3664          } elseif ( ! $test_themes_enabled && $theme_filter_present ) {
3665              return (object) array(
3666                  'status'  => 'recommended',
3667                  'message' => __( 'Auto-updates for themes appear to be disabled. This will prevent your site from receiving new versions automatically when available.' ),
3668              );
3669          }
3670  
3671          return (object) array(
3672              'status'  => 'good',
3673              'message' => __( 'There appear to be no issues with plugin and theme auto-updates.' ),
3674          );
3675      }
3676  
3677      /**
3678       * Runs a loopback test on the site.
3679       *
3680       * Loopbacks are what WordPress uses to communicate with itself to start up WP_Cron, scheduled posts,
3681       * make sure plugin or theme edits don't cause site failures and similar.
3682       *
3683       * @since 5.2.0
3684       *
3685       * @return object The test results.
3686       */
3687  	public function can_perform_loopback() {
3688          $body    = array( 'site-health' => 'loopback-test' );
3689          $cookies = wp_unslash( $_COOKIE );
3690          $timeout = 10; // 10 seconds.
3691          $headers = array(
3692              'Cache-Control' => 'no-cache',
3693          );
3694  
3695          // Include Basic auth in loopback requests.
3696          if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
3697              $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
3698          }
3699  
3700          $url = site_url( 'wp-cron.php' );
3701  
3702          /** This filter is documented in wp-includes/class-wp-http-streams.php */
3703          $sslverify = apply_filters( 'https_local_ssl_verify', false, $url );
3704  
3705          /*
3706           * A post request is used for the wp-cron.php loopback test to cause the file
3707           * to finish early without triggering cron jobs. This has two benefits:
3708           * - cron jobs are not triggered a second time on the site health page,
3709           * - the loopback request finishes sooner providing a quicker result.
3710           *
3711           * Using a POST request causes the loopback to differ slightly to the standard
3712           * GET request WordPress uses for wp-cron.php loopback requests but is close
3713           * enough. See https://core.trac.wordpress.org/ticket/52547
3714           */
3715          $r = wp_remote_post( $url, compact( 'body', 'cookies', 'headers', 'timeout', 'sslverify' ) );
3716  
3717          if ( is_wp_error( $r ) ) {
3718              return (object) array(
3719                  'status'  => 'critical',
3720                  'message' => sprintf(
3721                      '%s<br>%s',
3722                      __( 'The loopback request to your site failed, this means features relying on them are not currently working as expected.' ),
3723                      sprintf(
3724                          /* translators: 1: The WordPress error message. 2: The WordPress error code. */
3725                          __( 'Error: %1$s (%2$s)' ),
3726                          $r->get_error_message(),
3727                          $r->get_error_code()
3728                      )
3729                  ),
3730              );
3731          }
3732  
3733          if ( 200 !== wp_remote_retrieve_response_code( $r ) ) {
3734              return (object) array(
3735                  'status'  => 'recommended',
3736                  'message' => sprintf(
3737                      /* translators: %d: The HTTP response code returned. */
3738                      __( 'The loopback request returned an unexpected http status code, %d, it was not possible to determine if this will prevent features from working as expected.' ),
3739                      wp_remote_retrieve_response_code( $r )
3740                  ),
3741              );
3742          }
3743  
3744          return (object) array(
3745              'status'  => 'good',
3746              'message' => __( 'The loopback request to your site completed successfully.' ),
3747          );
3748      }
3749  
3750      /**
3751       * Creates a weekly cron event, if one does not already exist.
3752       *
3753       * @since 5.4.0
3754       */
3755  	public function maybe_create_scheduled_event() {
3756          if ( ! wp_next_scheduled( 'wp_site_health_scheduled_check' ) && ! wp_installing() ) {
3757              wp_schedule_event( time() + DAY_IN_SECONDS, 'weekly', 'wp_site_health_scheduled_check' );
3758          }
3759      }
3760  
3761      /**
3762       * Runs the scheduled event to check and update the latest site health status for the website.
3763       *
3764       * @since 5.4.0
3765       */
3766  	public function wp_cron_scheduled_check() {
3767          // Bootstrap wp-admin, as WP_Cron doesn't do this for us.
3768          require_once trailingslashit( ABSPATH ) . 'wp-admin/includes/admin.php';
3769  
3770          $tests = WP_Site_Health::get_tests();
3771  
3772          $results = array();
3773  
3774          $site_status = array(
3775              'good'        => 0,
3776              'recommended' => 0,
3777              'critical'    => 0,
3778          );
3779  
3780          // Don't run https test on development environments.
3781          if ( $this->is_development_environment() ) {
3782              unset( $tests['async']['https_status'] );
3783          }
3784  
3785          foreach ( $tests['direct'] as $test ) {
3786              if ( ! empty( $test['skip_cron'] ) ) {
3787                  continue;
3788              }
3789  
3790              if ( is_string( $test['test'] ) ) {
3791                  $test_function = sprintf(
3792                      'get_test_%s',
3793                      $test['test']
3794                  );
3795  
3796                  if ( method_exists( $this, $test_function ) && is_callable( array( $this, $test_function ) ) ) {
3797                      $results[] = $this->perform_test( array( $this, $test_function ) );
3798                      continue;
3799                  }
3800              }
3801  
3802              if ( is_callable( $test['test'] ) ) {
3803                  $results[] = $this->perform_test( $test['test'] );
3804              }
3805          }
3806  
3807          foreach ( $tests['async'] as $test ) {
3808              if ( ! empty( $test['skip_cron'] ) ) {
3809                  continue;
3810              }
3811  
3812              // Local endpoints may require authentication, so asynchronous tests can pass a direct test runner as well.
3813              if ( ! empty( $test['async_direct_test'] ) && is_callable( $test['async_direct_test'] ) ) {
3814                  // This test is callable, do so and continue to the next asynchronous check.
3815                  $results[] = $this->perform_test( $test['async_direct_test'] );
3816                  continue;
3817              }
3818  
3819              if ( is_string( $test['test'] ) ) {
3820                  // Check if this test has a REST API endpoint.
3821                  if ( isset( $test['has_rest'] ) && $test['has_rest'] ) {
3822                      $result_fetch = wp_remote_get(
3823                          $test['test'],
3824                          array(
3825                              'body' => array(
3826                                  '_wpnonce' => wp_create_nonce( 'wp_rest' ),
3827                              ),
3828                          )
3829                      );
3830                  } else {
3831                      $result_fetch = wp_remote_post(
3832                          admin_url( 'admin-ajax.php' ),
3833                          array(
3834                              'body' => array(
3835                                  'action'   => $test['test'],
3836                                  '_wpnonce' => wp_create_nonce( 'health-check-site-status' ),
3837                              ),
3838                          )
3839                      );
3840                  }
3841  
3842                  if ( ! is_wp_error( $result_fetch ) && 200 === wp_remote_retrieve_response_code( $result_fetch ) ) {
3843                      $result = json_decode( wp_remote_retrieve_body( $result_fetch ), true );
3844                  } else {
3845                      $result = false;
3846                  }
3847  
3848                  if ( is_array( $result ) ) {
3849                      $results[] = $result;
3850                  } else {
3851                      $results[] = array(
3852                          'status' => 'recommended',
3853                          'label'  => __( 'A test is unavailable' ),
3854                      );
3855                  }
3856              }
3857          }
3858  
3859          foreach ( $results as $result ) {
3860              if ( 'critical' === $result['status'] ) {
3861                  ++$site_status['critical'];
3862              } elseif ( 'recommended' === $result['status'] ) {
3863                  ++$site_status['recommended'];
3864              } else {
3865                  ++$site_status['good'];
3866              }
3867          }
3868  
3869          set_transient( 'health-check-site-status-result', wp_json_encode( $site_status ) );
3870      }
3871  
3872      /**
3873       * Checks if the current environment type is set to 'development' or 'local'.
3874       *
3875       * @since 5.6.0
3876       *
3877       * @return bool True if it is a development environment, false if not.
3878       */
3879  	public function is_development_environment() {
3880          return in_array( wp_get_environment_type(), array( 'development', 'local' ), true );
3881      }
3882  
3883      /**
3884       * Returns a mapping from response headers to an optional callback to verify if page cache is enabled or not.
3885       *
3886       * @since 6.1.0
3887       *
3888       * @return array<string, ?callable> Mapping of page caching headers and their (optional) verification callbacks.
3889       *                                  A null value means a simple existence check is used for the header.
3890       */
3891  	public function get_page_cache_headers(): array {
3892  
3893          $cache_hit_callback = static function ( $header_value ) {
3894              return 1 === preg_match( '/(^| |,)HIT(,| |$)/i', $header_value );
3895          };
3896  
3897          $cache_headers = array(
3898              // Standard HTTP caching headers.
3899              'cache-control'          => static function ( $header_value ) {
3900                  return (bool) preg_match( '/max-age=[1-9]/', $header_value );
3901              },
3902              'expires'                => static function ( $header_value ) {
3903                  return strtotime( $header_value ) > time();
3904              },
3905              'age'                    => static function ( $header_value ) {
3906                  return is_numeric( $header_value ) && $header_value > 0;
3907              },
3908              'last-modified'          => null,
3909              'etag'                   => null,
3910              'via'                    => null,
3911  
3912              /**
3913               * Custom caching headers.
3914               *
3915               * These do not seem to be actually used by any caching layers. There were first introduced in a Site Health
3916               * test in the AMP plugin. They were copied into the Performance Lab plugin's Site Health test before they
3917               * were merged into core.
3918               *
3919               * @link https://github.com/ampproject/amp-wp/pull/6849
3920               * @link https://github.com/WordPress/performance/pull/263
3921               * @link https://core.trac.wordpress.org/changeset/54043
3922               */
3923              'x-cache-enabled'        => static function ( $header_value ) {
3924                  return ( 'true' === strtolower( $header_value ) );
3925              },
3926              'x-cache-disabled'       => static function ( $header_value ) {
3927                  return ( 'on' !== strtolower( $header_value ) );
3928              },
3929  
3930              /**
3931               * CloudFlare.
3932               *
3933               * @link https://developers.cloudflare.com/cache/concepts/cache-responses/
3934               */
3935              'cf-cache-status'        => $cache_hit_callback,
3936  
3937              /**
3938               * Fastly.
3939               *
3940               * @link https://www.fastly.com/documentation/reference/http/http-headers/X-Cache/
3941               */
3942              'x-cache'                => $cache_hit_callback,
3943  
3944              /**
3945               * LightSpeed.
3946               *
3947               * @link https://docs.litespeedtech.com/lscache/devguide/controls/#x-litespeed-cache
3948               */
3949              'x-litespeed-cache'      => $cache_hit_callback,
3950  
3951              /**
3952               * OpenResty srcache-nginx-module.
3953               *
3954               * The `x-srcache-store-status` header indicates if the response was stored in the cache.
3955               * Valid values include `STORE` and `BYPASS`.
3956               *
3957               * The `x-srcache-fetch-status` header indicates if the response was fetched from the cache.
3958               * Valid values include `HIT`, `MISS`, and `BYPASS`.
3959               *
3960               * @link https://github.com/openresty/srcache-nginx-module
3961               */
3962              'x-srcache-store-status' => static function ( $header_value ) {
3963                  return 'store' === strtolower( $header_value );
3964              },
3965              'x-srcache-fetch-status' => $cache_hit_callback,
3966  
3967              /**
3968               * Nginx.
3969               *
3970               * @link https://blog.nginx.org/blog/nginx-caching-guide
3971               * @link https://www.inmotionhosting.com/support/website/nginx-cache-management/
3972               */
3973              'x-cache-status'         => $cache_hit_callback,
3974              'x-proxy-cache'          => $cache_hit_callback,
3975  
3976              /**
3977               * Varnish Cache.
3978               *
3979               * A header with a single number indicates it was not cached. If there are two numbers (or more), then this
3980               * indicates the response was cached.
3981               *
3982               * @link https://vinyl-cache.org/docs/2.1/faq/http.html
3983               * @link https://www.fastly.com/documentation/reference/http/http-headers/X-Varnish/
3984               * @link https://www.linuxjournal.com/content/speed-your-web-site-varnish
3985               */
3986              'x-varnish'              => static function ( $header_value ) {
3987                  return 1 === preg_match( '/^\d+ \d+/', $header_value );
3988              },
3989          );
3990  
3991          /**
3992           * Filters the list of cache headers supported by core.
3993           *
3994           * This list indicates how each of the specified headers will be checked to indicate if a page cache is enabled
3995           * or not. WordPress checks for each of the headers in the returned array. If the callback is provided, it will
3996           * be passed the value for the corresponding header and return a boolean value indicating if the header suggests
3997           * that a cache is active. If the value is `null` for the header, then WordPress will assume that a cache is
3998           * active if the header is present, regardless of its value.
3999           *
4000           * @since 6.1.0
4001           *
4002           * @param array<string, ?callable> $cache_headers Mapping from cache-related HTTP headers to whether they
4003           *                                                indicate if a page cache is enabled for the site. `null`
4004           *                                                indicates caching in the presence of the header; a callback is
4005           *                                                provided the header’s value and should return `true` if it
4006           *                                                implies that a cache is active.
4007           */
4008          return (array) apply_filters( 'site_status_page_cache_supported_cache_headers', $cache_headers );
4009      }
4010  
4011      /**
4012       * Checks if site has page cache enabled or not.
4013       *
4014       * @since 6.1.0
4015       *
4016       * @return WP_Error|array {
4017       *     Page cache detection details or else error information.
4018       *
4019       *     @type bool    $advanced_cache_present        Whether a page cache plugin is present.
4020       *     @type array[] $page_caching_response_headers Sets of client caching headers for the responses.
4021       *     @type float[] $response_timing               Response timings.
4022       * }
4023       */
4024  	private function check_for_page_caching() {
4025  
4026          /** This filter is documented in wp-includes/class-wp-http-streams.php */
4027          $sslverify = apply_filters( 'https_local_ssl_verify', false, home_url( '/' ) );
4028  
4029          $headers = array();
4030  
4031          /*
4032           * Include basic auth in loopback requests. Note that this will only pass along basic auth when user is
4033           * initiating the test. If a site requires basic auth, the test will fail when it runs in WP Cron as part of
4034           * wp_site_health_scheduled_check. This logic is copied from WP_Site_Health::can_perform_loopback().
4035           */
4036          if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
4037              $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
4038          }
4039  
4040          $caching_headers               = $this->get_page_cache_headers();
4041          $page_caching_response_headers = array();
4042          $response_timing               = array();
4043  
4044          for ( $i = 1; $i <= 3; $i++ ) {
4045              $start_time    = microtime( true );
4046              $http_response = wp_remote_get( home_url( '/' ), compact( 'sslverify', 'headers' ) );
4047              $end_time      = microtime( true );
4048  
4049              if ( is_wp_error( $http_response ) ) {
4050                  return $http_response;
4051              }
4052              if ( wp_remote_retrieve_response_code( $http_response ) !== 200 ) {
4053                  return new WP_Error(
4054                      'http_' . wp_remote_retrieve_response_code( $http_response ),
4055                      wp_remote_retrieve_response_message( $http_response )
4056                  );
4057              }
4058  
4059              $response_headers = array();
4060  
4061              foreach ( $caching_headers as $header => $callback ) {
4062                  $header_values = wp_remote_retrieve_header( $http_response, $header );
4063                  if ( empty( $header_values ) ) {
4064                      continue;
4065                  }
4066                  $header_values = (array) $header_values;
4067                  if ( empty( $callback ) || ( is_callable( $callback ) && count( array_filter( $header_values, $callback ) ) > 0 ) ) {
4068                      $response_headers[ $header ] = $header_values;
4069                  }
4070              }
4071  
4072              $page_caching_response_headers[] = $response_headers;
4073              $response_timing[]               = ( $end_time - $start_time ) * 1000;
4074          }
4075  
4076          return array(
4077              'advanced_cache_present'        => (
4078                  file_exists( WP_CONTENT_DIR . '/advanced-cache.php' )
4079                  &&
4080                  ( defined( 'WP_CACHE' ) && WP_CACHE )
4081                  &&
4082                  /** This filter is documented in wp-settings.php */
4083                  apply_filters( 'enable_loading_advanced_cache_dropin', true )
4084              ),
4085              'page_caching_response_headers' => $page_caching_response_headers,
4086              'response_timing'               => $response_timing,
4087          );
4088      }
4089  
4090      /**
4091       * Gets page cache details.
4092       *
4093       * @since 6.1.0
4094       *
4095       * @return WP_Error|array {
4096       *     Page cache detail or else a WP_Error if unable to determine.
4097       *
4098       *     @type string   $status                 Page cache status. Good, Recommended or Critical.
4099       *     @type bool     $advanced_cache_present Whether page cache plugin is available or not.
4100       *     @type string[] $headers                Client caching response headers detected.
4101       *     @type float    $response_time          Response time of site.
4102       * }
4103       */
4104  	private function get_page_cache_detail() {
4105          $page_cache_detail = $this->check_for_page_caching();
4106          if ( is_wp_error( $page_cache_detail ) ) {
4107              return $page_cache_detail;
4108          }
4109  
4110          // Use the median server response time.
4111          $response_timings = $page_cache_detail['response_timing'];
4112          rsort( $response_timings );
4113          $page_speed = $response_timings[ floor( count( $response_timings ) / 2 ) ];
4114  
4115          // Obtain unique set of all client caching response headers.
4116          $headers = array();
4117          foreach ( $page_cache_detail['page_caching_response_headers'] as $page_caching_response_headers ) {
4118              $headers = array_merge( $headers, array_keys( $page_caching_response_headers ) );
4119          }
4120          $headers = array_unique( $headers );
4121  
4122          // Page cache is detected if there are response headers or a page cache plugin is present.
4123          $has_page_caching = ( count( $headers ) > 0 || $page_cache_detail['advanced_cache_present'] );
4124  
4125          if ( $page_speed && $page_speed < $this->get_good_response_time_threshold() ) {
4126              $result = $has_page_caching ? 'good' : 'recommended';
4127          } else {
4128              $result = 'critical';
4129          }
4130  
4131          return array(
4132              'status'                 => $result,
4133              'advanced_cache_present' => $page_cache_detail['advanced_cache_present'],
4134              'headers'                => $headers,
4135              'response_time'          => $page_speed,
4136          );
4137      }
4138  
4139      /**
4140       * Gets the threshold below which a response time is considered good.
4141       *
4142       * @since 6.1.0
4143       *
4144       * @return int Threshold in milliseconds.
4145       */
4146  	private function get_good_response_time_threshold() {
4147          /**
4148           * Filters the threshold below which a response time is considered good.
4149           *
4150           * The default is based on https://web.dev/time-to-first-byte/.
4151           *
4152           * @since 6.1.0
4153           *
4154           * @param int $threshold Threshold in milliseconds. Default 600.
4155           */
4156          return (int) apply_filters( 'site_status_good_response_time_threshold', 600 );
4157      }
4158  
4159      /**
4160       * Determines whether to suggest using a persistent object cache.
4161       *
4162       * @since 6.1.0
4163       *
4164       * @global wpdb $wpdb WordPress database abstraction object.
4165       *
4166       * @return bool Whether to suggest using a persistent object cache.
4167       */
4168  	public function should_suggest_persistent_object_cache() {
4169          global $wpdb;
4170  
4171          /**
4172           * Filters whether to suggest use of a persistent object cache and bypass default threshold checks.
4173           *
4174           * Using this filter allows to override the default logic, effectively short-circuiting the method.
4175           *
4176           * @since 6.1.0
4177           *
4178           * @param bool|null $suggest Boolean to short-circuit, for whether to suggest using a persistent object cache.
4179           *                           Default null.
4180           */
4181          $short_circuit = apply_filters( 'site_status_should_suggest_persistent_object_cache', null );
4182          if ( is_bool( $short_circuit ) ) {
4183              return $short_circuit;
4184          }
4185  
4186          if ( is_multisite() ) {
4187              return true;
4188          }
4189  
4190          /**
4191           * Filters the thresholds used to determine whether to suggest the use of a persistent object cache.
4192           *
4193           * @since 6.1.0
4194           *
4195           * @param int[] $thresholds The list of threshold numbers keyed by threshold name.
4196           */
4197          $thresholds = apply_filters(
4198              'site_status_persistent_object_cache_thresholds',
4199              array(
4200                  'alloptions_count' => 500,
4201                  'alloptions_bytes' => 100000,
4202                  'comments_count'   => 1000,
4203                  'options_count'    => 1000,
4204                  'posts_count'      => 1000,
4205                  'terms_count'      => 1000,
4206                  'users_count'      => 1000,
4207              )
4208          );
4209  
4210          $alloptions = wp_load_alloptions();
4211  
4212          if ( $thresholds['alloptions_count'] < count( $alloptions ) ) {
4213              return true;
4214          }
4215  
4216          if ( $thresholds['alloptions_bytes'] < strlen( serialize( $alloptions ) ) ) {
4217              return true;
4218          }
4219  
4220          $table_names = implode( "','", array( $wpdb->comments, $wpdb->options, $wpdb->posts, $wpdb->terms, $wpdb->users ) );
4221  
4222          // With InnoDB the `TABLE_ROWS` are estimates, which are accurate enough and faster to retrieve than individual `COUNT()` queries.
4223          $results = $wpdb->get_results(
4224              $wpdb->prepare(
4225                  // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- This query cannot use interpolation.
4226                  "SELECT TABLE_NAME AS 'table', TABLE_ROWS AS 'rows', SUM(data_length + index_length) as 'bytes' FROM information_schema.TABLES WHERE TABLE_SCHEMA = %s AND TABLE_NAME IN ('$table_names') GROUP BY TABLE_NAME;",
4227                  DB_NAME
4228              ),
4229              OBJECT_K
4230          );
4231  
4232          $threshold_map = array(
4233              'comments_count' => $wpdb->comments,
4234              'options_count'  => $wpdb->options,
4235              'posts_count'    => $wpdb->posts,
4236              'terms_count'    => $wpdb->terms,
4237              'users_count'    => $wpdb->users,
4238          );
4239  
4240          return array_any( $threshold_map, fn( $table, $threshold ) => $thresholds[ $threshold ] <= $results[ $table ]->rows );
4241      }
4242  
4243      /**
4244       * Returns a list of available persistent object cache services.
4245       *
4246       * @since 6.1.0
4247       *
4248       * @return string[] The list of available persistent object cache services.
4249       */
4250  	private function available_object_cache_services() {
4251          $extensions = array_map(
4252              'extension_loaded',
4253              array(
4254                  'APCu'      => 'apcu',
4255                  'Redis'     => 'redis',
4256                  'Relay'     => 'relay',
4257                  'Memcache'  => 'memcache',
4258                  'Memcached' => 'memcached',
4259              )
4260          );
4261  
4262          $services = array_keys( array_filter( $extensions ) );
4263  
4264          /**
4265           * Filters the persistent object cache services available to the user.
4266           *
4267           * This can be useful to hide or add services not included in the defaults.
4268           *
4269           * @since 6.1.0
4270           *
4271           * @param string[] $services The list of available persistent object cache services.
4272           */
4273          return apply_filters( 'site_status_available_object_cache_services', $services );
4274      }
4275  }


Generated : Wed Nov 11 08:20:02 2026 Cross-referenced by PHPXref