PageRenderTime 48ms CodeModel.GetById 12ms app.highlight 26ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-admin/includes/class-wp-automatic-updater.php

http://github.com/wordpress/wordpress
PHP | 1016 lines | 579 code | 117 blank | 320 comment | 136 complexity | 428616b03be80f13d5626b5d3435ea29 MD5 | raw file
   1<?php
   2/**
   3 * Upgrade API: WP_Automatic_Updater class
   4 *
   5 * @package WordPress
   6 * @subpackage Upgrader
   7 * @since 4.6.0
   8 */
   9
  10/**
  11 * Core class used for handling automatic background updates.
  12 *
  13 * @since 3.7.0
  14 * @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader.php.
  15 */
  16class WP_Automatic_Updater {
  17
  18	/**
  19	 * Tracks update results during processing.
  20	 *
  21	 * @var array
  22	 */
  23	protected $update_results = array();
  24
  25	/**
  26	 * Whether the entire automatic updater is disabled.
  27	 *
  28	 * @since 3.7.0
  29	 */
  30	public function is_disabled() {
  31		// Background updates are disabled if you don't want file changes.
  32		if ( ! wp_is_file_mod_allowed( 'automatic_updater' ) ) {
  33			return true;
  34		}
  35
  36		if ( wp_installing() ) {
  37			return true;
  38		}
  39
  40		// More fine grained control can be done through the WP_AUTO_UPDATE_CORE constant and filters.
  41		$disabled = defined( 'AUTOMATIC_UPDATER_DISABLED' ) && AUTOMATIC_UPDATER_DISABLED;
  42
  43		/**
  44		 * Filters whether to entirely disable background updates.
  45		 *
  46		 * There are more fine-grained filters and controls for selective disabling.
  47		 * This filter parallels the AUTOMATIC_UPDATER_DISABLED constant in name.
  48		 *
  49		 * This also disables update notification emails. That may change in the future.
  50		 *
  51		 * @since 3.7.0
  52		 *
  53		 * @param bool $disabled Whether the updater should be disabled.
  54		 */
  55		return apply_filters( 'automatic_updater_disabled', $disabled );
  56	}
  57
  58	/**
  59	 * Check for version control checkouts.
  60	 *
  61	 * Checks for Subversion, Git, Mercurial, and Bazaar. It recursively looks up the
  62	 * filesystem to the top of the drive, erring on the side of detecting a VCS
  63	 * checkout somewhere.
  64	 *
  65	 * ABSPATH is always checked in addition to whatever $context is (which may be the
  66	 * wp-content directory, for example). The underlying assumption is that if you are
  67	 * using version control *anywhere*, then you should be making decisions for
  68	 * how things get updated.
  69	 *
  70	 * @since 3.7.0
  71	 *
  72	 * @param string $context The filesystem path to check, in addition to ABSPATH.
  73	 */
  74	public function is_vcs_checkout( $context ) {
  75		$context_dirs = array( untrailingslashit( $context ) );
  76		if ( ABSPATH !== $context ) {
  77			$context_dirs[] = untrailingslashit( ABSPATH );
  78		}
  79
  80		$vcs_dirs   = array( '.svn', '.git', '.hg', '.bzr' );
  81		$check_dirs = array();
  82
  83		foreach ( $context_dirs as $context_dir ) {
  84			// Walk up from $context_dir to the root.
  85			do {
  86				$check_dirs[] = $context_dir;
  87
  88				// Once we've hit '/' or 'C:\', we need to stop. dirname will keep returning the input here.
  89				if ( dirname( $context_dir ) === $context_dir ) {
  90					break;
  91				}
  92
  93				// Continue one level at a time.
  94			} while ( $context_dir = dirname( $context_dir ) );
  95		}
  96
  97		$check_dirs = array_unique( $check_dirs );
  98
  99		// Search all directories we've found for evidence of version control.
 100		foreach ( $vcs_dirs as $vcs_dir ) {
 101			foreach ( $check_dirs as $check_dir ) {
 102				$checkout = @is_dir( rtrim( $check_dir, '\\/' ) . "/$vcs_dir" );
 103				if ( $checkout ) {
 104					break 2;
 105				}
 106			}
 107		}
 108
 109		/**
 110		 * Filters whether the automatic updater should consider a filesystem
 111		 * location to be potentially managed by a version control system.
 112		 *
 113		 * @since 3.7.0
 114		 *
 115		 * @param bool $checkout  Whether a VCS checkout was discovered at $context
 116		 *                        or ABSPATH, or anywhere higher.
 117		 * @param string $context The filesystem context (a path) against which
 118		 *                        filesystem status should be checked.
 119		 */
 120		return apply_filters( 'automatic_updates_is_vcs_checkout', $checkout, $context );
 121	}
 122
 123	/**
 124	 * Tests to see if we can and should update a specific item.
 125	 *
 126	 * @since 3.7.0
 127	 *
 128	 * @global wpdb $wpdb WordPress database abstraction object.
 129	 *
 130	 * @param string $type    The type of update being checked: 'core', 'theme',
 131	 *                        'plugin', 'translation'.
 132	 * @param object $item    The update offer.
 133	 * @param string $context The filesystem context (a path) against which filesystem
 134	 *                        access and status should be checked.
 135	 */
 136	public function should_update( $type, $item, $context ) {
 137		// Used to see if WP_Filesystem is set up to allow unattended updates.
 138		$skin = new Automatic_Upgrader_Skin;
 139
 140		if ( $this->is_disabled() ) {
 141			return false;
 142		}
 143
 144		// Only relax the filesystem checks when the update doesn't include new files.
 145		$allow_relaxed_file_ownership = false;
 146		if ( 'core' == $type && isset( $item->new_files ) && ! $item->new_files ) {
 147			$allow_relaxed_file_ownership = true;
 148		}
 149
 150		// If we can't do an auto core update, we may still be able to email the user.
 151		if ( ! $skin->request_filesystem_credentials( false, $context, $allow_relaxed_file_ownership ) || $this->is_vcs_checkout( $context ) ) {
 152			if ( 'core' == $type ) {
 153				$this->send_core_update_notification_email( $item );
 154			}
 155			return false;
 156		}
 157
 158		// Next up, is this an item we can update?
 159		if ( 'core' == $type ) {
 160			$update = Core_Upgrader::should_update_to_version( $item->current );
 161		} else {
 162			$update = ! empty( $item->autoupdate );
 163		}
 164
 165		/**
 166		 * Filters whether to automatically update core, a plugin, a theme, or a language.
 167		 *
 168		 * The dynamic portion of the hook name, `$type`, refers to the type of update
 169		 * being checked. Can be 'core', 'theme', 'plugin', or 'translation'.
 170		 *
 171		 * Generally speaking, plugins, themes, and major core versions are not updated
 172		 * by default, while translations and minor and development versions for core
 173		 * are updated by default.
 174		 *
 175		 * See the {@see 'allow_dev_auto_core_updates'}, {@see 'allow_minor_auto_core_updates'},
 176		 * and {@see 'allow_major_auto_core_updates'} filters for a more straightforward way to
 177		 * adjust core updates.
 178		 *
 179		 * @since 3.7.0
 180		 *
 181		 * @param bool   $update Whether to update.
 182		 * @param object $item   The update offer.
 183		 */
 184		$update = apply_filters( "auto_update_{$type}", $update, $item );
 185
 186		if ( ! $update ) {
 187			if ( 'core' == $type ) {
 188				$this->send_core_update_notification_email( $item );
 189			}
 190			return false;
 191		}
 192
 193		// If it's a core update, are we actually compatible with its requirements?
 194		if ( 'core' == $type ) {
 195			global $wpdb;
 196
 197			$php_compat = version_compare( phpversion(), $item->php_version, '>=' );
 198			if ( file_exists( WP_CONTENT_DIR . '/db.php' ) && empty( $wpdb->is_mysql ) ) {
 199				$mysql_compat = true;
 200			} else {
 201				$mysql_compat = version_compare( $wpdb->db_version(), $item->mysql_version, '>=' );
 202			}
 203
 204			if ( ! $php_compat || ! $mysql_compat ) {
 205				return false;
 206			}
 207		}
 208
 209		// If updating a plugin, ensure the minimum PHP version requirements are satisfied.
 210		if ( 'plugin' === $type ) {
 211			if ( ! empty( $item->requires_php ) && version_compare( phpversion(), $item->requires_php, '<' ) ) {
 212				return false;
 213			}
 214		}
 215
 216		return true;
 217	}
 218
 219	/**
 220	 * Notifies an administrator of a core update.
 221	 *
 222	 * @since 3.7.0
 223	 *
 224	 * @param object $item The update offer.
 225	 */
 226	protected function send_core_update_notification_email( $item ) {
 227		$notified = get_site_option( 'auto_core_update_notified' );
 228
 229		// Don't notify if we've already notified the same email address of the same version.
 230		if ( $notified && get_site_option( 'admin_email' ) === $notified['email'] && $notified['version'] == $item->current ) {
 231			return false;
 232		}
 233
 234		// See if we need to notify users of a core update.
 235		$notify = ! empty( $item->notify_email );
 236
 237		/**
 238		 * Filters whether to notify the site administrator of a new core update.
 239		 *
 240		 * By default, administrators are notified when the update offer received
 241		 * from WordPress.org sets a particular flag. This allows some discretion
 242		 * in if and when to notify.
 243		 *
 244		 * This filter is only evaluated once per release. If the same email address
 245		 * was already notified of the same new version, WordPress won't repeatedly
 246		 * email the administrator.
 247		 *
 248		 * This filter is also used on about.php to check if a plugin has disabled
 249		 * these notifications.
 250		 *
 251		 * @since 3.7.0
 252		 *
 253		 * @param bool   $notify Whether the site administrator is notified.
 254		 * @param object $item   The update offer.
 255		 */
 256		if ( ! apply_filters( 'send_core_update_notification_email', $notify, $item ) ) {
 257			return false;
 258		}
 259
 260		$this->send_email( 'manual', $item );
 261		return true;
 262	}
 263
 264	/**
 265	 * Update an item, if appropriate.
 266	 *
 267	 * @since 3.7.0
 268	 *
 269	 * @param string $type The type of update being checked: 'core', 'theme', 'plugin', 'translation'.
 270	 * @param object $item The update offer.
 271	 *
 272	 * @return null|WP_Error
 273	 */
 274	public function update( $type, $item ) {
 275		$skin = new Automatic_Upgrader_Skin;
 276
 277		switch ( $type ) {
 278			case 'core':
 279				// The Core upgrader doesn't use the Upgrader's skin during the actual main part of the upgrade, instead, firing a filter.
 280				add_filter( 'update_feedback', array( $skin, 'feedback' ) );
 281				$upgrader = new Core_Upgrader( $skin );
 282				$context  = ABSPATH;
 283				break;
 284			case 'plugin':
 285				$upgrader = new Plugin_Upgrader( $skin );
 286				$context  = WP_PLUGIN_DIR; // We don't support custom Plugin directories, or updates for WPMU_PLUGIN_DIR.
 287				break;
 288			case 'theme':
 289				$upgrader = new Theme_Upgrader( $skin );
 290				$context  = get_theme_root( $item->theme );
 291				break;
 292			case 'translation':
 293				$upgrader = new Language_Pack_Upgrader( $skin );
 294				$context  = WP_CONTENT_DIR; // WP_LANG_DIR;
 295				break;
 296		}
 297
 298		// Determine whether we can and should perform this update.
 299		if ( ! $this->should_update( $type, $item, $context ) ) {
 300			return false;
 301		}
 302
 303		/**
 304		 * Fires immediately prior to an auto-update.
 305		 *
 306		 * @since 4.4.0
 307		 *
 308		 * @param string $type    The type of update being checked: 'core', 'theme', 'plugin', or 'translation'.
 309		 * @param object $item    The update offer.
 310		 * @param string $context The filesystem context (a path) against which filesystem access and status
 311		 *                        should be checked.
 312		 */
 313		do_action( 'pre_auto_update', $type, $item, $context );
 314
 315		$upgrader_item = $item;
 316		switch ( $type ) {
 317			case 'core':
 318				/* translators: %s: WordPress version. */
 319				$skin->feedback( __( 'Updating to WordPress %s' ), $item->version );
 320				/* translators: %s: WordPress version. */
 321				$item_name = sprintf( __( 'WordPress %s' ), $item->version );
 322				break;
 323			case 'theme':
 324				$upgrader_item = $item->theme;
 325				$theme         = wp_get_theme( $upgrader_item );
 326				$item_name     = $theme->Get( 'Name' );
 327				/* translators: %s: Theme name. */
 328				$skin->feedback( __( 'Updating theme: %s' ), $item_name );
 329				break;
 330			case 'plugin':
 331				$upgrader_item = $item->plugin;
 332				$plugin_data   = get_plugin_data( $context . '/' . $upgrader_item );
 333				$item_name     = $plugin_data['Name'];
 334				/* translators: %s: Plugin name. */
 335				$skin->feedback( __( 'Updating plugin: %s' ), $item_name );
 336				break;
 337			case 'translation':
 338				$language_item_name = $upgrader->get_name_for_update( $item );
 339				/* translators: %s: Project name (plugin, theme, or WordPress). */
 340				$item_name = sprintf( __( 'Translations for %s' ), $language_item_name );
 341				/* translators: 1: Project name (plugin, theme, or WordPress), 2: Language. */
 342				$skin->feedback( sprintf( __( 'Updating translations for %1$s (%2$s)&#8230;' ), $language_item_name, $item->language ) );
 343				break;
 344		}
 345
 346		$allow_relaxed_file_ownership = false;
 347		if ( 'core' == $type && isset( $item->new_files ) && ! $item->new_files ) {
 348			$allow_relaxed_file_ownership = true;
 349		}
 350
 351		// Boom, this site's about to get a whole new splash of paint!
 352		$upgrade_result = $upgrader->upgrade(
 353			$upgrader_item,
 354			array(
 355				'clear_update_cache'           => false,
 356				// Always use partial builds if possible for core updates.
 357				'pre_check_md5'                => false,
 358				// Only available for core updates.
 359				'attempt_rollback'             => true,
 360				// Allow relaxed file ownership in some scenarios.
 361				'allow_relaxed_file_ownership' => $allow_relaxed_file_ownership,
 362			)
 363		);
 364
 365		// If the filesystem is unavailable, false is returned.
 366		if ( false === $upgrade_result ) {
 367			$upgrade_result = new WP_Error( 'fs_unavailable', __( 'Could not access filesystem.' ) );
 368		}
 369
 370		if ( 'core' == $type ) {
 371			if ( is_wp_error( $upgrade_result ) && ( 'up_to_date' == $upgrade_result->get_error_code() || 'locked' == $upgrade_result->get_error_code() ) ) {
 372				// These aren't actual errors, treat it as a skipped-update instead to avoid triggering the post-core update failure routines.
 373				return false;
 374			}
 375
 376			// Core doesn't output this, so let's append it so we don't get confused.
 377			if ( is_wp_error( $upgrade_result ) ) {
 378				$skin->error( __( 'Installation Failed' ), $upgrade_result );
 379			} else {
 380				$skin->feedback( __( 'WordPress updated successfully' ) );
 381			}
 382		}
 383
 384		$this->update_results[ $type ][] = (object) array(
 385			'item'     => $item,
 386			'result'   => $upgrade_result,
 387			'name'     => $item_name,
 388			'messages' => $skin->get_upgrade_messages(),
 389		);
 390
 391		return $upgrade_result;
 392	}
 393
 394	/**
 395	 * Kicks off the background update process, looping through all pending updates.
 396	 *
 397	 * @since 3.7.0
 398	 */
 399	public function run() {
 400		if ( $this->is_disabled() ) {
 401			return;
 402		}
 403
 404		if ( ! is_main_network() || ! is_main_site() ) {
 405			return;
 406		}
 407
 408		if ( ! WP_Upgrader::create_lock( 'auto_updater' ) ) {
 409			return;
 410		}
 411
 412		// Don't automatically run these things, as we'll handle it ourselves.
 413		remove_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 );
 414		remove_action( 'upgrader_process_complete', 'wp_version_check' );
 415		remove_action( 'upgrader_process_complete', 'wp_update_plugins' );
 416		remove_action( 'upgrader_process_complete', 'wp_update_themes' );
 417
 418		// Next, plugins.
 419		wp_update_plugins(); // Check for plugin updates.
 420		$plugin_updates = get_site_transient( 'update_plugins' );
 421		if ( $plugin_updates && ! empty( $plugin_updates->response ) ) {
 422			foreach ( $plugin_updates->response as $plugin ) {
 423				$this->update( 'plugin', $plugin );
 424			}
 425			// Force refresh of plugin update information.
 426			wp_clean_plugins_cache();
 427		}
 428
 429		// Next, those themes we all love.
 430		wp_update_themes();  // Check for theme updates.
 431		$theme_updates = get_site_transient( 'update_themes' );
 432		if ( $theme_updates && ! empty( $theme_updates->response ) ) {
 433			foreach ( $theme_updates->response as $theme ) {
 434				$this->update( 'theme', (object) $theme );
 435			}
 436			// Force refresh of theme update information.
 437			wp_clean_themes_cache();
 438		}
 439
 440		// Next, process any core update.
 441		wp_version_check(); // Check for core updates.
 442		$core_update = find_core_auto_update();
 443
 444		if ( $core_update ) {
 445			$this->update( 'core', $core_update );
 446		}
 447
 448		// Clean up, and check for any pending translations.
 449		// (Core_Upgrader checks for core updates.)
 450		$theme_stats = array();
 451		if ( isset( $this->update_results['theme'] ) ) {
 452			foreach ( $this->update_results['theme'] as $upgrade ) {
 453				$theme_stats[ $upgrade->item->theme ] = ( true === $upgrade->result );
 454			}
 455		}
 456		wp_update_themes( $theme_stats ); // Check for theme updates.
 457
 458		$plugin_stats = array();
 459		if ( isset( $this->update_results['plugin'] ) ) {
 460			foreach ( $this->update_results['plugin'] as $upgrade ) {
 461				$plugin_stats[ $upgrade->item->plugin ] = ( true === $upgrade->result );
 462			}
 463		}
 464		wp_update_plugins( $plugin_stats ); // Check for plugin updates.
 465
 466		// Finally, process any new translations.
 467		$language_updates = wp_get_translation_updates();
 468		if ( $language_updates ) {
 469			foreach ( $language_updates as $update ) {
 470				$this->update( 'translation', $update );
 471			}
 472
 473			// Clear existing caches.
 474			wp_clean_update_cache();
 475
 476			wp_version_check();  // Check for core updates.
 477			wp_update_themes();  // Check for theme updates.
 478			wp_update_plugins(); // Check for plugin updates.
 479		}
 480
 481		// Send debugging email to admin for all development installations.
 482		if ( ! empty( $this->update_results ) ) {
 483			$development_version = false !== strpos( get_bloginfo( 'version' ), '-' );
 484
 485			/**
 486			 * Filters whether to send a debugging email for each automatic background update.
 487			 *
 488			 * @since 3.7.0
 489			 *
 490			 * @param bool $development_version By default, emails are sent if the
 491			 *                                  install is a development version.
 492			 *                                  Return false to avoid the email.
 493			 */
 494			if ( apply_filters( 'automatic_updates_send_debug_email', $development_version ) ) {
 495				$this->send_debug_email();
 496			}
 497
 498			if ( ! empty( $this->update_results['core'] ) ) {
 499				$this->after_core_update( $this->update_results['core'][0] );
 500			}
 501
 502			/**
 503			 * Fires after all automatic updates have run.
 504			 *
 505			 * @since 3.8.0
 506			 *
 507			 * @param array $update_results The results of all attempted updates.
 508			 */
 509			do_action( 'automatic_updates_complete', $this->update_results );
 510		}
 511
 512		WP_Upgrader::release_lock( 'auto_updater' );
 513	}
 514
 515	/**
 516	 * If we tried to perform a core update, check if we should send an email,
 517	 * and if we need to avoid processing future updates.
 518	 *
 519	 * @since 3.7.0
 520	 *
 521	 * @param object $update_result The result of the core update. Includes the update offer and result.
 522	 */
 523	protected function after_core_update( $update_result ) {
 524		$wp_version = get_bloginfo( 'version' );
 525
 526		$core_update = $update_result->item;
 527		$result      = $update_result->result;
 528
 529		if ( ! is_wp_error( $result ) ) {
 530			$this->send_email( 'success', $core_update );
 531			return;
 532		}
 533
 534		$error_code = $result->get_error_code();
 535
 536		// Any of these WP_Error codes are critical failures, as in they occurred after we started to copy core files.
 537		// We should not try to perform a background update again until there is a successful one-click update performed by the user.
 538		$critical = false;
 539		if ( 'disk_full' === $error_code || false !== strpos( $error_code, '__copy_dir' ) ) {
 540			$critical = true;
 541		} elseif ( 'rollback_was_required' === $error_code && is_wp_error( $result->get_error_data()->rollback ) ) {
 542			// A rollback is only critical if it failed too.
 543			$critical        = true;
 544			$rollback_result = $result->get_error_data()->rollback;
 545		} elseif ( false !== strpos( $error_code, 'do_rollback' ) ) {
 546			$critical = true;
 547		}
 548
 549		if ( $critical ) {
 550			$critical_data = array(
 551				'attempted'  => $core_update->current,
 552				'current'    => $wp_version,
 553				'error_code' => $error_code,
 554				'error_data' => $result->get_error_data(),
 555				'timestamp'  => time(),
 556				'critical'   => true,
 557			);
 558			if ( isset( $rollback_result ) ) {
 559				$critical_data['rollback_code'] = $rollback_result->get_error_code();
 560				$critical_data['rollback_data'] = $rollback_result->get_error_data();
 561			}
 562			update_site_option( 'auto_core_update_failed', $critical_data );
 563			$this->send_email( 'critical', $core_update, $result );
 564			return;
 565		}
 566
 567		/*
 568		 * Any other WP_Error code (like download_failed or files_not_writable) occurs before
 569		 * we tried to copy over core files. Thus, the failures are early and graceful.
 570		 *
 571		 * We should avoid trying to perform a background update again for the same version.
 572		 * But we can try again if another version is released.
 573		 *
 574		 * For certain 'transient' failures, like download_failed, we should allow retries.
 575		 * In fact, let's schedule a special update for an hour from now. (It's possible
 576		 * the issue could actually be on WordPress.org's side.) If that one fails, then email.
 577		 */
 578		$send               = true;
 579		$transient_failures = array( 'incompatible_archive', 'download_failed', 'insane_distro', 'locked' );
 580		if ( in_array( $error_code, $transient_failures, true ) && ! get_site_option( 'auto_core_update_failed' ) ) {
 581			wp_schedule_single_event( time() + HOUR_IN_SECONDS, 'wp_maybe_auto_update' );
 582			$send = false;
 583		}
 584
 585		$n = get_site_option( 'auto_core_update_notified' );
 586		// Don't notify if we've already notified the same email address of the same version of the same notification type.
 587		if ( $n && 'fail' === $n['type'] && get_site_option( 'admin_email' ) === $n['email'] && $n['version'] == $core_update->current ) {
 588			$send = false;
 589		}
 590
 591		update_site_option(
 592			'auto_core_update_failed',
 593			array(
 594				'attempted'  => $core_update->current,
 595				'current'    => $wp_version,
 596				'error_code' => $error_code,
 597				'error_data' => $result->get_error_data(),
 598				'timestamp'  => time(),
 599				'retry'      => in_array( $error_code, $transient_failures, true ),
 600			)
 601		);
 602
 603		if ( $send ) {
 604			$this->send_email( 'fail', $core_update, $result );
 605		}
 606	}
 607
 608	/**
 609	 * Sends an email upon the completion or failure of a background core update.
 610	 *
 611	 * @since 3.7.0
 612	 *
 613	 * @param string $type        The type of email to send. Can be one of 'success', 'fail', 'manual', 'critical'.
 614	 * @param object $core_update The update offer that was attempted.
 615	 * @param mixed  $result      Optional. The result for the core update. Can be WP_Error.
 616	 */
 617	protected function send_email( $type, $core_update, $result = null ) {
 618		update_site_option(
 619			'auto_core_update_notified',
 620			array(
 621				'type'      => $type,
 622				'email'     => get_site_option( 'admin_email' ),
 623				'version'   => $core_update->current,
 624				'timestamp' => time(),
 625			)
 626		);
 627
 628		$next_user_core_update = get_preferred_from_update_core();
 629		// If the update transient is empty, use the update we just performed.
 630		if ( ! $next_user_core_update ) {
 631			$next_user_core_update = $core_update;
 632		}
 633		$newer_version_available = ( 'upgrade' == $next_user_core_update->response && version_compare( $next_user_core_update->version, $core_update->version, '>' ) );
 634
 635		/**
 636		 * Filters whether to send an email following an automatic background core update.
 637		 *
 638		 * @since 3.7.0
 639		 *
 640		 * @param bool   $send        Whether to send the email. Default true.
 641		 * @param string $type        The type of email to send. Can be one of
 642		 *                            'success', 'fail', 'critical'.
 643		 * @param object $core_update The update offer that was attempted.
 644		 * @param mixed  $result      The result for the core update. Can be WP_Error.
 645		 */
 646		if ( 'manual' !== $type && ! apply_filters( 'auto_core_update_send_email', true, $type, $core_update, $result ) ) {
 647			return;
 648		}
 649
 650		switch ( $type ) {
 651			case 'success': // We updated.
 652				/* translators: Site updated notification email subject. 1: Site title, 2: WordPress version. */
 653				$subject = __( '[%1$s] Your site has updated to WordPress %2$s' );
 654				break;
 655
 656			case 'fail':   // We tried to update but couldn't.
 657			case 'manual': // We can't update (and made no attempt).
 658				/* translators: Update available notification email subject. 1: Site title, 2: WordPress version. */
 659				$subject = __( '[%1$s] WordPress %2$s is available. Please update!' );
 660				break;
 661
 662			case 'critical': // We tried to update, started to copy files, then things went wrong.
 663				/* translators: Site down notification email subject. 1: Site title. */
 664				$subject = __( '[%1$s] URGENT: Your site may be down due to a failed update' );
 665				break;
 666
 667			default:
 668				return;
 669		}
 670
 671		// If the auto update is not to the latest version, say that the current version of WP is available instead.
 672		$version = 'success' === $type ? $core_update->current : $next_user_core_update->current;
 673		$subject = sprintf( $subject, wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ), $version );
 674
 675		$body = '';
 676
 677		switch ( $type ) {
 678			case 'success':
 679				$body .= sprintf(
 680					/* translators: 1: Home URL, 2: WordPress version. */
 681					__( 'Howdy! Your site at %1$s has been updated automatically to WordPress %2$s.' ),
 682					home_url(),
 683					$core_update->current
 684				);
 685				$body .= "\n\n";
 686				if ( ! $newer_version_available ) {
 687					$body .= __( 'No further action is needed on your part.' ) . ' ';
 688				}
 689
 690				// Can only reference the About screen if their update was successful.
 691				list( $about_version ) = explode( '-', $core_update->current, 2 );
 692				/* translators: %s: WordPress version. */
 693				$body .= sprintf( __( 'For more on version %s, see the About WordPress screen:' ), $about_version );
 694				$body .= "\n" . admin_url( 'about.php' );
 695
 696				if ( $newer_version_available ) {
 697					/* translators: %s: WordPress latest version. */
 698					$body .= "\n\n" . sprintf( __( 'WordPress %s is also now available.' ), $next_user_core_update->current ) . ' ';
 699					$body .= __( 'Updating is easy and only takes a few moments:' );
 700					$body .= "\n" . network_admin_url( 'update-core.php' );
 701				}
 702
 703				break;
 704
 705			case 'fail':
 706			case 'manual':
 707				$body .= sprintf(
 708					/* translators: 1: Home URL, 2: WordPress version. */
 709					__( 'Please update your site at %1$s to WordPress %2$s.' ),
 710					home_url(),
 711					$next_user_core_update->current
 712				);
 713
 714				$body .= "\n\n";
 715
 716				// Don't show this message if there is a newer version available.
 717				// Potential for confusion, and also not useful for them to know at this point.
 718				if ( 'fail' == $type && ! $newer_version_available ) {
 719					$body .= __( 'We tried but were unable to update your site automatically.' ) . ' ';
 720				}
 721
 722				$body .= __( 'Updating is easy and only takes a few moments:' );
 723				$body .= "\n" . network_admin_url( 'update-core.php' );
 724				break;
 725
 726			case 'critical':
 727				if ( $newer_version_available ) {
 728					$body .= sprintf(
 729						/* translators: 1: Home URL, 2: WordPress version. */
 730						__( 'Your site at %1$s experienced a critical failure while trying to update WordPress to version %2$s.' ),
 731						home_url(),
 732						$core_update->current
 733					);
 734				} else {
 735					$body .= sprintf(
 736						/* translators: 1: Home URL, 2: WordPress latest version. */
 737						__( 'Your site at %1$s experienced a critical failure while trying to update to the latest version of WordPress, %2$s.' ),
 738						home_url(),
 739						$core_update->current
 740					);
 741				}
 742
 743				$body .= "\n\n" . __( "This means your site may be offline or broken. Don't panic; this can be fixed." );
 744
 745				$body .= "\n\n" . __( "Please check out your site now. It's possible that everything is working. If it says you need to update, you should do so:" );
 746				$body .= "\n" . network_admin_url( 'update-core.php' );
 747				break;
 748		}
 749
 750		$critical_support = 'critical' === $type && ! empty( $core_update->support_email );
 751		if ( $critical_support ) {
 752			// Support offer if available.
 753			$body .= "\n\n" . sprintf(
 754				/* translators: %s: Support email address. */
 755				__( 'The WordPress team is willing to help you. Forward this email to %s and the team will work with you to make sure your site is working.' ),
 756				$core_update->support_email
 757			);
 758		} else {
 759			// Add a note about the support forums.
 760			$body .= "\n\n" . __( 'If you experience any issues or need support, the volunteers in the WordPress.org support forums may be able to help.' );
 761			$body .= "\n" . __( 'https://wordpress.org/support/forums/' );
 762		}
 763
 764		// Updates are important!
 765		if ( 'success' !== $type || $newer_version_available ) {
 766			$body .= "\n\n" . __( 'Keeping your site updated is important for security. It also makes the internet a safer place for you and your readers.' );
 767		}
 768
 769		if ( $critical_support ) {
 770			$body .= ' ' . __( "If you reach out to us, we'll also ensure you'll never have this problem again." );
 771		}
 772
 773		// If things are successful and we're now on the latest, mention plugins and themes if any are out of date.
 774		if ( 'success' === $type && ! $newer_version_available && ( get_plugin_updates() || get_theme_updates() ) ) {
 775			$body .= "\n\n" . __( 'You also have some plugins or themes with updates available. Update them now:' );
 776			$body .= "\n" . network_admin_url();
 777		}
 778
 779		$body .= "\n\n" . __( 'The WordPress Team' ) . "\n";
 780
 781		if ( 'critical' == $type && is_wp_error( $result ) ) {
 782			$body .= "\n***\n\n";
 783			/* translators: %s: WordPress version. */
 784			$body .= sprintf( __( 'Your site was running version %s.' ), get_bloginfo( 'version' ) );
 785			$body .= ' ' . __( 'We have some data that describes the error your site encountered.' );
 786			$body .= ' ' . __( 'Your hosting company, support forum volunteers, or a friendly developer may be able to use this information to help you:' );
 787
 788			// If we had a rollback and we're still critical, then the rollback failed too.
 789			// Loop through all errors (the main WP_Error, the update result, the rollback result) for code, data, etc.
 790			if ( 'rollback_was_required' == $result->get_error_code() ) {
 791				$errors = array( $result, $result->get_error_data()->update, $result->get_error_data()->rollback );
 792			} else {
 793				$errors = array( $result );
 794			}
 795
 796			foreach ( $errors as $error ) {
 797				if ( ! is_wp_error( $error ) ) {
 798					continue;
 799				}
 800				$error_code = $error->get_error_code();
 801				/* translators: %s: Error code. */
 802				$body .= "\n\n" . sprintf( __( 'Error code: %s' ), $error_code );
 803				if ( 'rollback_was_required' == $error_code ) {
 804					continue;
 805				}
 806				if ( $error->get_error_message() ) {
 807					$body .= "\n" . $error->get_error_message();
 808				}
 809				$error_data = $error->get_error_data();
 810				if ( $error_data ) {
 811					$body .= "\n" . implode( ', ', (array) $error_data );
 812				}
 813			}
 814			$body .= "\n";
 815		}
 816
 817		$to      = get_site_option( 'admin_email' );
 818		$headers = '';
 819
 820		$email = compact( 'to', 'subject', 'body', 'headers' );
 821
 822		/**
 823		 * Filters the email sent following an automatic background core update.
 824		 *
 825		 * @since 3.7.0
 826		 *
 827		 * @param array $email {
 828		 *     Array of email arguments that will be passed to wp_mail().
 829		 *
 830		 *     @type string $to      The email recipient. An array of emails
 831		 *                            can be returned, as handled by wp_mail().
 832		 *     @type string $subject The email's subject.
 833		 *     @type string $body    The email message body.
 834		 *     @type string $headers Any email headers, defaults to no headers.
 835		 * }
 836		 * @param string $type        The type of email being sent. Can be one of
 837		 *                            'success', 'fail', 'manual', 'critical'.
 838		 * @param object $core_update The update offer that was attempted.
 839		 * @param mixed  $result      The result for the core update. Can be WP_Error.
 840		 */
 841		$email = apply_filters( 'auto_core_update_email', $email, $type, $core_update, $result );
 842
 843		wp_mail( $email['to'], wp_specialchars_decode( $email['subject'] ), $email['body'], $email['headers'] );
 844	}
 845
 846	/**
 847	 * Prepares and sends an email of a full log of background update results, useful for debugging and geekery.
 848	 *
 849	 * @since 3.7.0
 850	 */
 851	protected function send_debug_email() {
 852		$update_count = 0;
 853		foreach ( $this->update_results as $type => $updates ) {
 854			$update_count += count( $updates );
 855		}
 856
 857		$body     = array();
 858		$failures = 0;
 859
 860		/* translators: %s: Network home URL. */
 861		$body[] = sprintf( __( 'WordPress site: %s' ), network_home_url( '/' ) );
 862
 863		// Core.
 864		if ( isset( $this->update_results['core'] ) ) {
 865			$result = $this->update_results['core'][0];
 866			if ( $result->result && ! is_wp_error( $result->result ) ) {
 867				/* translators: %s: WordPress version. */
 868				$body[] = sprintf( __( 'SUCCESS: WordPress was successfully updated to %s' ), $result->name );
 869			} else {
 870				/* translators: %s: WordPress version. */
 871				$body[] = sprintf( __( 'FAILED: WordPress failed to update to %s' ), $result->name );
 872				$failures++;
 873			}
 874			$body[] = '';
 875		}
 876
 877		// Plugins, Themes, Translations.
 878		foreach ( array( 'plugin', 'theme', 'translation' ) as $type ) {
 879			if ( ! isset( $this->update_results[ $type ] ) ) {
 880				continue;
 881			}
 882			$success_items = wp_list_filter( $this->update_results[ $type ], array( 'result' => true ) );
 883			if ( $success_items ) {
 884				$messages = array(
 885					'plugin'      => __( 'The following plugins were successfully updated:' ),
 886					'theme'       => __( 'The following themes were successfully updated:' ),
 887					'translation' => __( 'The following translations were successfully updated:' ),
 888				);
 889
 890				$body[] = $messages[ $type ];
 891				foreach ( wp_list_pluck( $success_items, 'name' ) as $name ) {
 892					/* translators: %s: Name of plugin / theme / translation. */
 893					$body[] = ' * ' . sprintf( __( 'SUCCESS: %s' ), $name );
 894				}
 895			}
 896			if ( $success_items != $this->update_results[ $type ] ) {
 897				// Failed updates.
 898				$messages = array(
 899					'plugin'      => __( 'The following plugins failed to update:' ),
 900					'theme'       => __( 'The following themes failed to update:' ),
 901					'translation' => __( 'The following translations failed to update:' ),
 902				);
 903
 904				$body[] = $messages[ $type ];
 905				foreach ( $this->update_results[ $type ] as $item ) {
 906					if ( ! $item->result || is_wp_error( $item->result ) ) {
 907						/* translators: %s: Name of plugin / theme / translation. */
 908						$body[] = ' * ' . sprintf( __( 'FAILED: %s' ), $item->name );
 909						$failures++;
 910					}
 911				}
 912			}
 913			$body[] = '';
 914		}
 915
 916		$site_title = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );
 917		if ( $failures ) {
 918			$body[] = trim(
 919				__(
 920					"BETA TESTING?
 921=============
 922
 923This debugging email is sent when you are using a development version of WordPress.
 924
 925If you think these failures might be due to a bug in WordPress, could you report it?
 926 * Open a thread in the support forums: https://wordpress.org/support/forum/alphabeta
 927 * Or, if you're comfortable writing a bug report: https://core.trac.wordpress.org/
 928
 929Thanks! -- The WordPress Team"
 930				)
 931			);
 932			$body[] = '';
 933
 934			/* translators: Background update failed notification email subject. %s: Site title. */
 935			$subject = sprintf( __( '[%s] Background Update Failed' ), $site_title );
 936		} else {
 937			/* translators: Background update finished notification email subject. %s: Site title. */
 938			$subject = sprintf( __( '[%s] Background Update Finished' ), $site_title );
 939		}
 940
 941		$body[] = trim(
 942			__(
 943				'UPDATE LOG
 944=========='
 945			)
 946		);
 947		$body[] = '';
 948
 949		foreach ( array( 'core', 'plugin', 'theme', 'translation' ) as $type ) {
 950			if ( ! isset( $this->update_results[ $type ] ) ) {
 951				continue;
 952			}
 953			foreach ( $this->update_results[ $type ] as $update ) {
 954				$body[] = $update->name;
 955				$body[] = str_repeat( '-', strlen( $update->name ) );
 956				foreach ( $update->messages as $message ) {
 957					$body[] = '  ' . html_entity_decode( str_replace( '&#8230;', '...', $message ) );
 958				}
 959				if ( is_wp_error( $update->result ) ) {
 960					$results = array( 'update' => $update->result );
 961					// If we rolled back, we want to know an error that occurred then too.
 962					if ( 'rollback_was_required' === $update->result->get_error_code() ) {
 963						$results = (array) $update->result->get_error_data();
 964					}
 965					foreach ( $results as $result_type => $result ) {
 966						if ( ! is_wp_error( $result ) ) {
 967							continue;
 968						}
 969
 970						if ( 'rollback' === $result_type ) {
 971							/* translators: 1: Error code, 2: Error message. */
 972							$body[] = '  ' . sprintf( __( 'Rollback Error: [%1$s] %2$s' ), $result->get_error_code(), $result->get_error_message() );
 973						} else {
 974							/* translators: 1: Error code, 2: Error message. */
 975							$body[] = '  ' . sprintf( __( 'Error: [%1$s] %2$s' ), $result->get_error_code(), $result->get_error_message() );
 976						}
 977
 978						if ( $result->get_error_data() ) {
 979							$body[] = '         ' . implode( ', ', (array) $result->get_error_data() );
 980						}
 981					}
 982				}
 983				$body[] = '';
 984			}
 985		}
 986
 987		$email = array(
 988			'to'      => get_site_option( 'admin_email' ),
 989			'subject' => $subject,
 990			'body'    => implode( "\n", $body ),
 991			'headers' => '',
 992		);
 993
 994		/**
 995		 * Filters the debug email that can be sent following an automatic
 996		 * background core update.
 997		 *
 998		 * @since 3.8.0
 999		 *
1000		 * @param array $email {
1001		 *     Array of email arguments that will be passed to wp_mail().
1002		 *
1003		 *     @type string $to      The email recipient. An array of emails
1004		 *                           can be returned, as handled by wp_mail().
1005		 *     @type string $subject Email subject.
1006		 *     @type string $body    Email message body.
1007		 *     @type string $headers Any email headers. Default empty.
1008		 * }
1009		 * @param int   $failures The number of failures encountered while upgrading.
1010		 * @param mixed $results  The results of all attempted updates.
1011		 */
1012		$email = apply_filters( 'automatic_updates_debug_email', $email, $failures, $this->update_results );
1013
1014		wp_mail( $email['to'], wp_specialchars_decode( $email['subject'] ), $email['body'], $email['headers'] );
1015	}
1016}