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