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