WordPress 3.9
[autoinstalls/wordpress.git] / wp-admin / includes / class-wp-upgrader.php
1 <?php
2 /**
3  * A File upgrader class for WordPress.
4  *
5  * This set of classes are designed to be used to upgrade/install a local set of files on the filesystem via the Filesystem Abstraction classes.
6  *
7  * @link http://trac.wordpress.org/ticket/7875 consolidate plugin/theme/core upgrade/install functions
8  *
9  * @package WordPress
10  * @subpackage Upgrader
11  * @since 2.8.0
12  */
13
14 require ABSPATH . 'wp-admin/includes/class-wp-upgrader-skins.php';
15
16 /**
17  * WordPress Upgrader class for Upgrading/Installing a local set of files via the Filesystem Abstraction classes from a Zip file.
18  *
19  * @package WordPress
20  * @subpackage Upgrader
21  * @since 2.8.0
22  */
23 class WP_Upgrader {
24         var $strings = array();
25         var $skin = null;
26         var $result = array();
27
28         function __construct($skin = null) {
29                 if ( null == $skin )
30                         $this->skin = new WP_Upgrader_Skin();
31                 else
32                         $this->skin = $skin;
33         }
34
35         function init() {
36                 $this->skin->set_upgrader($this);
37                 $this->generic_strings();
38         }
39
40         function generic_strings() {
41                 $this->strings['bad_request'] = __('Invalid Data provided.');
42                 $this->strings['fs_unavailable'] = __('Could not access filesystem.');
43                 $this->strings['fs_error'] = __('Filesystem error.');
44                 $this->strings['fs_no_root_dir'] = __('Unable to locate WordPress Root directory.');
45                 $this->strings['fs_no_content_dir'] = __('Unable to locate WordPress Content directory (wp-content).');
46                 $this->strings['fs_no_plugins_dir'] = __('Unable to locate WordPress Plugin directory.');
47                 $this->strings['fs_no_themes_dir'] = __('Unable to locate WordPress Theme directory.');
48                 /* translators: %s: directory name */
49                 $this->strings['fs_no_folder'] = __('Unable to locate needed folder (%s).');
50
51                 $this->strings['download_failed'] = __('Download failed.');
52                 $this->strings['installing_package'] = __('Installing the latest version&#8230;');
53                 $this->strings['no_files'] = __('The package contains no files.');
54                 $this->strings['folder_exists'] = __('Destination folder already exists.');
55                 $this->strings['mkdir_failed'] = __('Could not create directory.');
56                 $this->strings['incompatible_archive'] = __('The package could not be installed.');
57
58                 $this->strings['maintenance_start'] = __('Enabling Maintenance mode&#8230;');
59                 $this->strings['maintenance_end'] = __('Disabling Maintenance mode&#8230;');
60         }
61
62         function fs_connect( $directories = array() ) {
63                 global $wp_filesystem;
64
65                 if ( false === ($credentials = $this->skin->request_filesystem_credentials()) )
66                         return false;
67
68                 if ( ! WP_Filesystem($credentials) ) {
69                         $error = true;
70                         if ( is_object($wp_filesystem) && $wp_filesystem->errors->get_error_code() )
71                                 $error = $wp_filesystem->errors;
72                         $this->skin->request_filesystem_credentials($error); //Failed to connect, Error and request again
73                         return false;
74                 }
75
76                 if ( ! is_object($wp_filesystem) )
77                         return new WP_Error('fs_unavailable', $this->strings['fs_unavailable'] );
78
79                 if ( is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code() )
80                         return new WP_Error('fs_error', $this->strings['fs_error'], $wp_filesystem->errors);
81
82                 foreach ( (array)$directories as $dir ) {
83                         switch ( $dir ) {
84                                 case ABSPATH:
85                                         if ( ! $wp_filesystem->abspath() )
86                                                 return new WP_Error('fs_no_root_dir', $this->strings['fs_no_root_dir']);
87                                         break;
88                                 case WP_CONTENT_DIR:
89                                         if ( ! $wp_filesystem->wp_content_dir() )
90                                                 return new WP_Error('fs_no_content_dir', $this->strings['fs_no_content_dir']);
91                                         break;
92                                 case WP_PLUGIN_DIR:
93                                         if ( ! $wp_filesystem->wp_plugins_dir() )
94                                                 return new WP_Error('fs_no_plugins_dir', $this->strings['fs_no_plugins_dir']);
95                                         break;
96                                 case get_theme_root():
97                                         if ( ! $wp_filesystem->wp_themes_dir() )
98                                                 return new WP_Error('fs_no_themes_dir', $this->strings['fs_no_themes_dir']);
99                                         break;
100                                 default:
101                                         if ( ! $wp_filesystem->find_folder($dir) )
102                                                 return new WP_Error( 'fs_no_folder', sprintf( $this->strings['fs_no_folder'], esc_html( basename( $dir ) ) ) );
103                                         break;
104                         }
105                 }
106                 return true;
107         } //end fs_connect();
108
109         function download_package($package) {
110
111                 /**
112                  * Filter whether to return the package.
113                  *
114                  * @since 3.7.0
115                  *
116                  * @param bool        $reply   Whether to bail without returning the package.
117                  *                             Default false.
118                  * @param string      $package The package file name.
119                  * @param WP_Upgrader $this    The WP_Upgrader instance.
120                  */
121                 $reply = apply_filters( 'upgrader_pre_download', false, $package, $this );
122                 if ( false !== $reply )
123                         return $reply;
124
125                 if ( ! preg_match('!^(http|https|ftp)://!i', $package) && file_exists($package) ) //Local file or remote?
126                         return $package; //must be a local file..
127
128                 if ( empty($package) )
129                         return new WP_Error('no_package', $this->strings['no_package']);
130
131                 $this->skin->feedback('downloading_package', $package);
132
133                 $download_file = download_url($package);
134
135                 if ( is_wp_error($download_file) )
136                         return new WP_Error('download_failed', $this->strings['download_failed'], $download_file->get_error_message());
137
138                 return $download_file;
139         }
140
141         function unpack_package($package, $delete_package = true) {
142                 global $wp_filesystem;
143
144                 $this->skin->feedback('unpack_package');
145
146                 $upgrade_folder = $wp_filesystem->wp_content_dir() . 'upgrade/';
147
148                 //Clean up contents of upgrade directory beforehand.
149                 $upgrade_files = $wp_filesystem->dirlist($upgrade_folder);
150                 if ( !empty($upgrade_files) ) {
151                         foreach ( $upgrade_files as $file )
152                                 $wp_filesystem->delete($upgrade_folder . $file['name'], true);
153                 }
154
155                 //We need a working directory
156                 $working_dir = $upgrade_folder . basename($package, '.zip');
157
158                 // Clean up working directory
159                 if ( $wp_filesystem->is_dir($working_dir) )
160                         $wp_filesystem->delete($working_dir, true);
161
162                 // Unzip package to working directory
163                 $result = unzip_file( $package, $working_dir );
164
165                 // Once extracted, delete the package if required.
166                 if ( $delete_package )
167                         unlink($package);
168
169                 if ( is_wp_error($result) ) {
170                         $wp_filesystem->delete($working_dir, true);
171                         if ( 'incompatible_archive' == $result->get_error_code() ) {
172                                 return new WP_Error( 'incompatible_archive', $this->strings['incompatible_archive'], $result->get_error_data() );
173                         }
174                         return $result;
175                 }
176
177                 return $working_dir;
178         }
179
180         function install_package( $args = array() ) {
181                 global $wp_filesystem, $wp_theme_directories;
182
183                 $defaults = array(
184                         'source' => '', // Please always pass this
185                         'destination' => '', // and this
186                         'clear_destination' => false,
187                         'clear_working' => false,
188                         'abort_if_destination_exists' => true,
189                         'hook_extra' => array()
190                 );
191
192                 $args = wp_parse_args($args, $defaults);
193                 extract($args);
194
195                 @set_time_limit( 300 );
196
197                 if ( empty($source) || empty($destination) )
198                         return new WP_Error('bad_request', $this->strings['bad_request']);
199
200                 $this->skin->feedback('installing_package');
201
202                 /**
203                  * Filter the install response before the installation has started.
204                  *
205                  * Returning a truthy value, or one that could be evaluated as a WP_Error
206                  * will effectively short-circuit the installation, returning that value
207                  * instead.
208                  *
209                  * @since 2.8.0
210                  *
211                  * @param bool|WP_Error $response   Response.
212                  * @param array         $hook_extra Extra arguments passed to hooked filters.
213                  */
214                 $res = apply_filters( 'upgrader_pre_install', true, $hook_extra );
215                 if ( is_wp_error($res) )
216                         return $res;
217
218                 //Retain the Original source and destinations
219                 $remote_source = $source;
220                 $local_destination = $destination;
221
222                 $source_files = array_keys( $wp_filesystem->dirlist($remote_source) );
223                 $remote_destination = $wp_filesystem->find_folder($local_destination);
224
225                 //Locate which directory to copy to the new folder, This is based on the actual folder holding the files.
226                 if ( 1 == count($source_files) && $wp_filesystem->is_dir( trailingslashit($source) . $source_files[0] . '/') ) //Only one folder? Then we want its contents.
227                         $source = trailingslashit($source) . trailingslashit($source_files[0]);
228                 elseif ( count($source_files) == 0 )
229                         return new WP_Error( 'incompatible_archive_empty', $this->strings['incompatible_archive'], $this->strings['no_files'] ); // There are no files?
230                 else //It's only a single file, the upgrader will use the foldername of this file as the destination folder. foldername is based on zip filename.
231                         $source = trailingslashit($source);
232
233                 /**
234                  * Filter the source file location for the upgrade package.
235                  *
236                  * @since 2.8.0
237                  *
238                  * @param string      $source        File source location.
239                  * @param string      $remote_source Remove file source location.
240                  * @param WP_Upgrader $this          WP_Upgrader instance.
241                  */
242                 $source = apply_filters( 'upgrader_source_selection', $source, $remote_source, $this );
243                 if ( is_wp_error($source) )
244                         return $source;
245
246                 //Has the source location changed? If so, we need a new source_files list.
247                 if ( $source !== $remote_source )
248                         $source_files = array_keys( $wp_filesystem->dirlist($source) );
249
250                 // Protection against deleting files in any important base directories.
251                 // Theme_Upgrader & Plugin_Upgrader also trigger this, as they pass the destination directory (WP_PLUGIN_DIR / wp-content/themes)
252                 // intending to copy the directory into the directory, whilst they pass the source as the actual files to copy.
253                 $protected_directories = array( ABSPATH, WP_CONTENT_DIR, WP_PLUGIN_DIR, WP_CONTENT_DIR . '/themes' );
254                 if ( is_array( $wp_theme_directories ) )
255                         $protected_directories = array_merge( $protected_directories, $wp_theme_directories );
256                 if ( in_array( $destination, $protected_directories ) ) {
257                         $remote_destination = trailingslashit($remote_destination) . trailingslashit(basename($source));
258                         $destination = trailingslashit($destination) . trailingslashit(basename($source));
259                 }
260
261                 if ( $clear_destination ) {
262                         //We're going to clear the destination if there's something there
263                         $this->skin->feedback('remove_old');
264                         $removed = true;
265                         if ( $wp_filesystem->exists($remote_destination) )
266                                 $removed = $wp_filesystem->delete($remote_destination, true);
267
268                         /**
269                          * Filter whether the upgrader cleared the destination.
270                          *
271                          * @since 2.8.0
272                          *
273                          * @param bool   $removed            Whether the destination was cleared.
274                          * @param string $local_destination  The local package destination.
275                          * @param string $remote_destination The remote package destination.
276                          * @param array  $hook_extra         Extra arguments passed to hooked filters.
277                          */
278                         $removed = apply_filters( 'upgrader_clear_destination', $removed, $local_destination, $remote_destination, $hook_extra );
279
280                         if ( is_wp_error($removed) )
281                                 return $removed;
282                         else if ( ! $removed )
283                                 return new WP_Error('remove_old_failed', $this->strings['remove_old_failed']);
284                 } elseif ( $abort_if_destination_exists && $wp_filesystem->exists($remote_destination) ) {
285                         //If we're not clearing the destination folder and something exists there already, Bail.
286                         //But first check to see if there are actually any files in the folder.
287                         $_files = $wp_filesystem->dirlist($remote_destination);
288                         if ( ! empty($_files) ) {
289                                 $wp_filesystem->delete($remote_source, true); //Clear out the source files.
290                                 return new WP_Error('folder_exists', $this->strings['folder_exists'], $remote_destination );
291                         }
292                 }
293
294                 //Create destination if needed
295                 if ( !$wp_filesystem->exists($remote_destination) )
296                         if ( !$wp_filesystem->mkdir($remote_destination, FS_CHMOD_DIR) )
297                                 return new WP_Error( 'mkdir_failed_destination', $this->strings['mkdir_failed'], $remote_destination );
298
299                 // Copy new version of item into place.
300                 $result = copy_dir($source, $remote_destination);
301                 if ( is_wp_error($result) ) {
302                         if ( $clear_working )
303                                 $wp_filesystem->delete($remote_source, true);
304                         return $result;
305                 }
306
307                 //Clear the Working folder?
308                 if ( $clear_working )
309                         $wp_filesystem->delete($remote_source, true);
310
311                 $destination_name = basename( str_replace($local_destination, '', $destination) );
312                 if ( '.' == $destination_name )
313                         $destination_name = '';
314
315                 $this->result = compact('local_source', 'source', 'source_name', 'source_files', 'destination', 'destination_name', 'local_destination', 'remote_destination', 'clear_destination', 'delete_source_dir');
316
317                 /**
318                  * Filter the install response after the installation has finished.
319                  *
320                  * @since 2.8.0
321                  *
322                  * @param bool  $response   Install response.
323                  * @param array $hook_extra Extra arguments passed to hooked filters.
324                  * @param array $result     Installation result data.
325                  */
326                 $res = apply_filters( 'upgrader_post_install', true, $hook_extra, $this->result );
327
328                 if ( is_wp_error($res) ) {
329                         $this->result = $res;
330                         return $res;
331                 }
332
333                 //Bombard the calling function will all the info which we've just used.
334                 return $this->result;
335         }
336
337         function run($options) {
338
339                 $defaults = array(
340                         'package' => '', // Please always pass this.
341                         'destination' => '', // And this
342                         'clear_destination' => false,
343                         'abort_if_destination_exists' => true, // Abort if the Destination directory exists, Pass clear_destination as false please
344                         'clear_working' => true,
345                         'is_multi' => false,
346                         'hook_extra' => array() // Pass any extra $hook_extra args here, this will be passed to any hooked filters.
347                 );
348
349                 $options = wp_parse_args($options, $defaults);
350                 extract($options);
351
352                 if ( ! $is_multi ) // call $this->header separately if running multiple times
353                         $this->skin->header();
354
355                 // Connect to the Filesystem first.
356                 $res = $this->fs_connect( array(WP_CONTENT_DIR, $destination) );
357                 // Mainly for non-connected filesystem.
358                 if ( ! $res ) {
359                         if ( ! $is_multi )
360                                 $this->skin->footer();
361                         return false;
362                 }
363
364                 $this->skin->before();
365
366                 if ( is_wp_error($res) ) {
367                         $this->skin->error($res);
368                         $this->skin->after();
369                         if ( ! $is_multi )
370                                 $this->skin->footer();
371                         return $res;
372                 }
373
374                 //Download the package (Note, This just returns the filename of the file if the package is a local file)
375                 $download = $this->download_package( $package );
376                 if ( is_wp_error($download) ) {
377                         $this->skin->error($download);
378                         $this->skin->after();
379                         if ( ! $is_multi )
380                                 $this->skin->footer();
381                         return $download;
382                 }
383
384                 $delete_package = ($download != $package); // Do not delete a "local" file
385
386                 //Unzips the file into a temporary directory
387                 $working_dir = $this->unpack_package( $download, $delete_package );
388                 if ( is_wp_error($working_dir) ) {
389                         $this->skin->error($working_dir);
390                         $this->skin->after();
391                         if ( ! $is_multi )
392                                 $this->skin->footer();
393                         return $working_dir;
394                 }
395
396                 //With the given options, this installs it to the destination directory.
397                 $result = $this->install_package( array(
398                         'source' => $working_dir,
399                         'destination' => $destination,
400                         'clear_destination' => $clear_destination,
401                         'abort_if_destination_exists' => $abort_if_destination_exists,
402                         'clear_working' => $clear_working,
403                         'hook_extra' => $hook_extra
404                 ) );
405
406                 $this->skin->set_result($result);
407                 if ( is_wp_error($result) ) {
408                         $this->skin->error($result);
409                         $this->skin->feedback('process_failed');
410                 } else {
411                         //Install Succeeded
412                         $this->skin->feedback('process_success');
413                 }
414
415                 $this->skin->after();
416
417                 if ( ! $is_multi ) {
418
419                         /** This action is documented in wp-admin/includes/class-wp-upgrader.php */
420                         do_action( 'upgrader_process_complete', $this, $hook_extra );
421                         $this->skin->footer();
422                 }
423
424                 return $result;
425         }
426
427         function maintenance_mode($enable = false) {
428                 global $wp_filesystem;
429                 $file = $wp_filesystem->abspath() . '.maintenance';
430                 if ( $enable ) {
431                         $this->skin->feedback('maintenance_start');
432                         // Create maintenance file to signal that we are upgrading
433                         $maintenance_string = '<?php $upgrading = ' . time() . '; ?>';
434                         $wp_filesystem->delete($file);
435                         $wp_filesystem->put_contents($file, $maintenance_string, FS_CHMOD_FILE);
436                 } else if ( !$enable && $wp_filesystem->exists($file) ) {
437                         $this->skin->feedback('maintenance_end');
438                         $wp_filesystem->delete($file);
439                 }
440         }
441
442 }
443
444 /**
445  * Plugin Upgrader class for WordPress Plugins, It is designed to upgrade/install plugins from a local zip, remote zip URL, or uploaded zip file.
446  *
447  * @package WordPress
448  * @subpackage Upgrader
449  * @since 2.8.0
450  */
451 class Plugin_Upgrader extends WP_Upgrader {
452
453         var $result;
454         var $bulk = false;
455
456         function upgrade_strings() {
457                 $this->strings['up_to_date'] = __('The plugin is at the latest version.');
458                 $this->strings['no_package'] = __('Update package not available.');
459                 $this->strings['downloading_package'] = __('Downloading update from <span class="code">%s</span>&#8230;');
460                 $this->strings['unpack_package'] = __('Unpacking the update&#8230;');
461                 $this->strings['remove_old'] = __('Removing the old version of the plugin&#8230;');
462                 $this->strings['remove_old_failed'] = __('Could not remove the old plugin.');
463                 $this->strings['process_failed'] = __('Plugin update failed.');
464                 $this->strings['process_success'] = __('Plugin updated successfully.');
465         }
466
467         function install_strings() {
468                 $this->strings['no_package'] = __('Install package not available.');
469                 $this->strings['downloading_package'] = __('Downloading install package from <span class="code">%s</span>&#8230;');
470                 $this->strings['unpack_package'] = __('Unpacking the package&#8230;');
471                 $this->strings['installing_package'] = __('Installing the plugin&#8230;');
472                 $this->strings['no_files'] = __('The plugin contains no files.');
473                 $this->strings['process_failed'] = __('Plugin install failed.');
474                 $this->strings['process_success'] = __('Plugin installed successfully.');
475         }
476
477         function install( $package, $args = array() ) {
478
479                 $defaults = array(
480                         'clear_update_cache' => true,
481                 );
482                 $parsed_args = wp_parse_args( $args, $defaults );
483
484                 $this->init();
485                 $this->install_strings();
486
487                 add_filter('upgrader_source_selection', array($this, 'check_package') );
488
489                 $this->run( array(
490                         'package' => $package,
491                         'destination' => WP_PLUGIN_DIR,
492                         'clear_destination' => false, // Do not overwrite files.
493                         'clear_working' => true,
494                         'hook_extra' => array(
495                                 'type' => 'plugin',
496                                 'action' => 'install',
497                         )
498                 ) );
499
500                 remove_filter('upgrader_source_selection', array($this, 'check_package') );
501
502                 if ( ! $this->result || is_wp_error($this->result) )
503                         return $this->result;
504
505                 // Force refresh of plugin update information
506                 wp_clean_plugins_cache( $parsed_args['clear_update_cache'] );
507
508                 return true;
509         }
510
511         function upgrade( $plugin, $args = array() ) {
512
513                 $defaults = array(
514                         'clear_update_cache' => true,
515                 );
516                 $parsed_args = wp_parse_args( $args, $defaults );
517
518                 $this->init();
519                 $this->upgrade_strings();
520
521                 $current = get_site_transient( 'update_plugins' );
522                 if ( !isset( $current->response[ $plugin ] ) ) {
523                         $this->skin->before();
524                         $this->skin->set_result(false);
525                         $this->skin->error('up_to_date');
526                         $this->skin->after();
527                         return false;
528                 }
529
530                 // Get the URL to the zip file
531                 $r = $current->response[ $plugin ];
532
533                 add_filter('upgrader_pre_install', array($this, 'deactivate_plugin_before_upgrade'), 10, 2);
534                 add_filter('upgrader_clear_destination', array($this, 'delete_old_plugin'), 10, 4);
535                 //'source_selection' => array($this, 'source_selection'), //there's a trac ticket to move up the directory for zip's which are made a bit differently, useful for non-.org plugins.
536
537                 $this->run( array(
538                         'package' => $r->package,
539                         'destination' => WP_PLUGIN_DIR,
540                         'clear_destination' => true,
541                         'clear_working' => true,
542                         'hook_extra' => array(
543                                 'plugin' => $plugin,
544                                 'type' => 'plugin',
545                                 'action' => 'update',
546                         ),
547                 ) );
548
549                 // Cleanup our hooks, in case something else does a upgrade on this connection.
550                 remove_filter('upgrader_pre_install', array($this, 'deactivate_plugin_before_upgrade'));
551                 remove_filter('upgrader_clear_destination', array($this, 'delete_old_plugin'));
552
553                 if ( ! $this->result || is_wp_error($this->result) )
554                         return $this->result;
555
556                 // Force refresh of plugin update information
557                 wp_clean_plugins_cache( $parsed_args['clear_update_cache'] );
558
559                 return true;
560         }
561
562         function bulk_upgrade( $plugins, $args = array() ) {
563
564                 $defaults = array(
565                         'clear_update_cache' => true,
566                 );
567                 $parsed_args = wp_parse_args( $args, $defaults );
568
569                 $this->init();
570                 $this->bulk = true;
571                 $this->upgrade_strings();
572
573                 $current = get_site_transient( 'update_plugins' );
574
575                 add_filter('upgrader_clear_destination', array($this, 'delete_old_plugin'), 10, 4);
576
577                 $this->skin->header();
578
579                 // Connect to the Filesystem first.
580                 $res = $this->fs_connect( array(WP_CONTENT_DIR, WP_PLUGIN_DIR) );
581                 if ( ! $res ) {
582                         $this->skin->footer();
583                         return false;
584                 }
585
586                 $this->skin->bulk_header();
587
588                 // Only start maintenance mode if:
589                 // - running Multisite and there are one or more plugins specified, OR
590                 // - a plugin with an update available is currently active.
591                 // @TODO: For multisite, maintenance mode should only kick in for individual sites if at all possible.
592                 $maintenance = ( is_multisite() && ! empty( $plugins ) );
593                 foreach ( $plugins as $plugin )
594                         $maintenance = $maintenance || ( is_plugin_active( $plugin ) && isset( $current->response[ $plugin] ) );
595                 if ( $maintenance )
596                         $this->maintenance_mode(true);
597
598                 $results = array();
599
600                 $this->update_count = count($plugins);
601                 $this->update_current = 0;
602                 foreach ( $plugins as $plugin ) {
603                         $this->update_current++;
604                         $this->skin->plugin_info = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin, false, true);
605
606                         if ( !isset( $current->response[ $plugin ] ) ) {
607                                 $this->skin->set_result('up_to_date');
608                                 $this->skin->before();
609                                 $this->skin->feedback('up_to_date');
610                                 $this->skin->after();
611                                 $results[$plugin] = true;
612                                 continue;
613                         }
614
615                         // Get the URL to the zip file
616                         $r = $current->response[ $plugin ];
617
618                         $this->skin->plugin_active = is_plugin_active($plugin);
619
620                         $result = $this->run( array(
621                                 'package' => $r->package,
622                                 'destination' => WP_PLUGIN_DIR,
623                                 'clear_destination' => true,
624                                 'clear_working' => true,
625                                 'is_multi' => true,
626                                 'hook_extra' => array(
627                                         'plugin' => $plugin
628                                 )
629                         ) );
630
631                         $results[$plugin] = $this->result;
632
633                         // Prevent credentials auth screen from displaying multiple times
634                         if ( false === $result )
635                                 break;
636                 } //end foreach $plugins
637
638                 $this->maintenance_mode(false);
639
640                 /**
641                  * Fires when the bulk upgrader process is complete.
642                  *
643                  * @since 3.6.0
644                  *
645                  * @param Plugin_Upgrader $this Plugin_Upgrader instance. In other contexts, $this, might
646                  *                              be a Theme_Upgrader or Core_Upgrade instance.
647                  * @param array           $data {
648                  *     Array of bulk item update data.
649                  *
650                  *     @type string $action   Type of action. Default 'update'.
651                  *     @type string $type     Type of update process. Accepts 'plugin', 'theme', or 'core'.
652                  *     @type bool   $bulk     Whether the update process is a bulk update. Default true.
653                  *     @type array  $packages Array of plugin, theme, or core packages to update.
654                  * }
655                  */
656                 do_action( 'upgrader_process_complete', $this, array(
657                         'action' => 'update',
658                         'type' => 'plugin',
659                         'bulk' => true,
660                         'plugins' => $plugins,
661                 ) );
662
663                 $this->skin->bulk_footer();
664
665                 $this->skin->footer();
666
667                 // Cleanup our hooks, in case something else does a upgrade on this connection.
668                 remove_filter('upgrader_clear_destination', array($this, 'delete_old_plugin'));
669
670                 // Force refresh of plugin update information
671                 wp_clean_plugins_cache( $parsed_args['clear_update_cache'] );
672
673                 return $results;
674         }
675
676         function check_package($source) {
677                 global $wp_filesystem;
678
679                 if ( is_wp_error($source) )
680                         return $source;
681
682                 $working_directory = str_replace( $wp_filesystem->wp_content_dir(), trailingslashit(WP_CONTENT_DIR), $source);
683                 if ( ! is_dir($working_directory) ) // Sanity check, if the above fails, lets not prevent installation.
684                         return $source;
685
686                 // Check the folder contains at least 1 valid plugin.
687                 $plugins_found = false;
688                 foreach ( glob( $working_directory . '*.php' ) as $file ) {
689                         $info = get_plugin_data($file, false, false);
690                         if ( !empty( $info['Name'] ) ) {
691                                 $plugins_found = true;
692                                 break;
693                         }
694                 }
695
696                 if ( ! $plugins_found )
697                         return new WP_Error( 'incompatible_archive_no_plugins', $this->strings['incompatible_archive'], __( 'No valid plugins were found.' ) );
698
699                 return $source;
700         }
701
702         //return plugin info.
703         function plugin_info() {
704                 if ( ! is_array($this->result) )
705                         return false;
706                 if ( empty($this->result['destination_name']) )
707                         return false;
708
709                 $plugin = get_plugins('/' . $this->result['destination_name']); //Ensure to pass with leading slash
710                 if ( empty($plugin) )
711                         return false;
712
713                 $pluginfiles = array_keys($plugin); //Assume the requested plugin is the first in the list
714
715                 return $this->result['destination_name'] . '/' . $pluginfiles[0];
716         }
717
718         //Hooked to pre_install
719         function deactivate_plugin_before_upgrade($return, $plugin) {
720
721                 if ( is_wp_error($return) ) //Bypass.
722                         return $return;
723
724                 // When in cron (background updates) don't deactivate the plugin, as we require a browser to reactivate it
725                 if ( defined( 'DOING_CRON' ) && DOING_CRON )
726                         return $return;
727
728                 $plugin = isset($plugin['plugin']) ? $plugin['plugin'] : '';
729                 if ( empty($plugin) )
730                         return new WP_Error('bad_request', $this->strings['bad_request']);
731
732                 if ( is_plugin_active($plugin) ) {
733                         //Deactivate the plugin silently, Prevent deactivation hooks from running.
734                         deactivate_plugins($plugin, true);
735                 }
736         }
737
738         //Hooked to upgrade_clear_destination
739         function delete_old_plugin($removed, $local_destination, $remote_destination, $plugin) {
740                 global $wp_filesystem;
741
742                 if ( is_wp_error($removed) )
743                         return $removed; //Pass errors through.
744
745                 $plugin = isset($plugin['plugin']) ? $plugin['plugin'] : '';
746                 if ( empty($plugin) )
747                         return new WP_Error('bad_request', $this->strings['bad_request']);
748
749                 $plugins_dir = $wp_filesystem->wp_plugins_dir();
750                 $this_plugin_dir = trailingslashit( dirname($plugins_dir . $plugin) );
751
752                 if ( ! $wp_filesystem->exists($this_plugin_dir) ) //If it's already vanished.
753                         return $removed;
754
755                 // If plugin is in its own directory, recursively delete the directory.
756                 if ( strpos($plugin, '/') && $this_plugin_dir != $plugins_dir ) //base check on if plugin includes directory separator AND that it's not the root plugin folder
757                         $deleted = $wp_filesystem->delete($this_plugin_dir, true);
758                 else
759                         $deleted = $wp_filesystem->delete($plugins_dir . $plugin);
760
761                 if ( ! $deleted )
762                         return new WP_Error('remove_old_failed', $this->strings['remove_old_failed']);
763
764                 return true;
765         }
766 }
767
768 /**
769  * Theme Upgrader class for WordPress Themes, It is designed to upgrade/install themes from a local zip, remote zip URL, or uploaded zip file.
770  *
771  * @package WordPress
772  * @subpackage Upgrader
773  * @since 2.8.0
774  */
775 class Theme_Upgrader extends WP_Upgrader {
776
777         var $result;
778         var $bulk = false;
779
780         function upgrade_strings() {
781                 $this->strings['up_to_date'] = __('The theme is at the latest version.');
782                 $this->strings['no_package'] = __('Update package not available.');
783                 $this->strings['downloading_package'] = __('Downloading update from <span class="code">%s</span>&#8230;');
784                 $this->strings['unpack_package'] = __('Unpacking the update&#8230;');
785                 $this->strings['remove_old'] = __('Removing the old version of the theme&#8230;');
786                 $this->strings['remove_old_failed'] = __('Could not remove the old theme.');
787                 $this->strings['process_failed'] = __('Theme update failed.');
788                 $this->strings['process_success'] = __('Theme updated successfully.');
789         }
790
791         function install_strings() {
792                 $this->strings['no_package'] = __('Install package not available.');
793                 $this->strings['downloading_package'] = __('Downloading install package from <span class="code">%s</span>&#8230;');
794                 $this->strings['unpack_package'] = __('Unpacking the package&#8230;');
795                 $this->strings['installing_package'] = __('Installing the theme&#8230;');
796                 $this->strings['no_files'] = __('The theme contains no files.');
797                 $this->strings['process_failed'] = __('Theme install failed.');
798                 $this->strings['process_success'] = __('Theme installed successfully.');
799                 /* translators: 1: theme name, 2: version */
800                 $this->strings['process_success_specific'] = __('Successfully installed the theme <strong>%1$s %2$s</strong>.');
801                 $this->strings['parent_theme_search'] = __('This theme requires a parent theme. Checking if it is installed&#8230;');
802                 /* translators: 1: theme name, 2: version */
803                 $this->strings['parent_theme_prepare_install'] = __('Preparing to install <strong>%1$s %2$s</strong>&#8230;');
804                 /* translators: 1: theme name, 2: version */
805                 $this->strings['parent_theme_currently_installed'] = __('The parent theme, <strong>%1$s %2$s</strong>, is currently installed.');
806                 /* translators: 1: theme name, 2: version */
807                 $this->strings['parent_theme_install_success'] = __('Successfully installed the parent theme, <strong>%1$s %2$s</strong>.');
808                 $this->strings['parent_theme_not_found'] = __('<strong>The parent theme could not be found.</strong> You will need to install the parent theme, <strong>%s</strong>, before you can use this child theme.');
809         }
810
811         function check_parent_theme_filter($install_result, $hook_extra, $child_result) {
812                 // Check to see if we need to install a parent theme
813                 $theme_info = $this->theme_info();
814
815                 if ( ! $theme_info->parent() )
816                         return $install_result;
817
818                 $this->skin->feedback( 'parent_theme_search' );
819
820                 if ( ! $theme_info->parent()->errors() ) {
821                         $this->skin->feedback( 'parent_theme_currently_installed', $theme_info->parent()->display('Name'), $theme_info->parent()->display('Version') );
822                         // We already have the theme, fall through.
823                         return $install_result;
824                 }
825
826                 // We don't have the parent theme, lets install it
827                 $api = themes_api('theme_information', array('slug' => $theme_info->get('Template'), 'fields' => array('sections' => false, 'tags' => false) ) ); //Save on a bit of bandwidth.
828
829                 if ( ! $api || is_wp_error($api) ) {
830                         $this->skin->feedback( 'parent_theme_not_found', $theme_info->get('Template') );
831                         // Don't show activate or preview actions after install
832                         add_filter('install_theme_complete_actions', array($this, 'hide_activate_preview_actions') );
833                         return $install_result;
834                 }
835
836                 // Backup required data we're going to override:
837                 $child_api = $this->skin->api;
838                 $child_success_message = $this->strings['process_success'];
839
840                 // Override them
841                 $this->skin->api = $api;
842                 $this->strings['process_success_specific'] = $this->strings['parent_theme_install_success'];//, $api->name, $api->version);
843
844                 $this->skin->feedback('parent_theme_prepare_install', $api->name, $api->version);
845
846                 add_filter('install_theme_complete_actions', '__return_false', 999); // Don't show any actions after installing the theme.
847
848                 // Install the parent theme
849                 $parent_result = $this->run( array(
850                         'package' => $api->download_link,
851                         'destination' => get_theme_root(),
852                         'clear_destination' => false, //Do not overwrite files.
853                         'clear_working' => true
854                 ) );
855
856                 if ( is_wp_error($parent_result) )
857                         add_filter('install_theme_complete_actions', array($this, 'hide_activate_preview_actions') );
858
859                 // Start cleaning up after the parents installation
860                 remove_filter('install_theme_complete_actions', '__return_false', 999);
861
862                 // Reset child's result and data
863                 $this->result = $child_result;
864                 $this->skin->api = $child_api;
865                 $this->strings['process_success'] = $child_success_message;
866
867                 return $install_result;
868         }
869
870         function hide_activate_preview_actions($actions) {
871                 unset($actions['activate'], $actions['preview']);
872                 return $actions;
873         }
874
875         function install( $package, $args = array() ) {
876
877                 $defaults = array(
878                         'clear_update_cache' => true,
879                 );
880                 $parsed_args = wp_parse_args( $args, $defaults );
881
882                 $this->init();
883                 $this->install_strings();
884
885                 add_filter('upgrader_source_selection', array($this, 'check_package') );
886                 add_filter('upgrader_post_install', array($this, 'check_parent_theme_filter'), 10, 3);
887
888                 $this->run( array(
889                         'package' => $package,
890                         'destination' => get_theme_root(),
891                         'clear_destination' => false, //Do not overwrite files.
892                         'clear_working' => true,
893                         'hook_extra' => array(
894                                 'type' => 'theme',
895                                 'action' => 'install',
896                         ),
897                 ) );
898
899                 remove_filter('upgrader_source_selection', array($this, 'check_package') );
900                 remove_filter('upgrader_post_install', array($this, 'check_parent_theme_filter'));
901
902                 if ( ! $this->result || is_wp_error($this->result) )
903                         return $this->result;
904
905                 // Refresh the Theme Update information
906                 wp_clean_themes_cache( $parsed_args['clear_update_cache'] );
907
908                 return true;
909         }
910
911         function upgrade( $theme, $args = array() ) {
912
913                 $defaults = array(
914                         'clear_update_cache' => true,
915                 );
916                 $parsed_args = wp_parse_args( $args, $defaults );
917
918                 $this->init();
919                 $this->upgrade_strings();
920
921                 // Is an update available?
922                 $current = get_site_transient( 'update_themes' );
923                 if ( !isset( $current->response[ $theme ] ) ) {
924                         $this->skin->before();
925                         $this->skin->set_result(false);
926                         $this->skin->error( 'up_to_date' );
927                         $this->skin->after();
928                         return false;
929                 }
930
931                 $r = $current->response[ $theme ];
932
933                 add_filter('upgrader_pre_install', array($this, 'current_before'), 10, 2);
934                 add_filter('upgrader_post_install', array($this, 'current_after'), 10, 2);
935                 add_filter('upgrader_clear_destination', array($this, 'delete_old_theme'), 10, 4);
936
937                 $this->run( array(
938                         'package' => $r['package'],
939                         'destination' => get_theme_root( $theme ),
940                         'clear_destination' => true,
941                         'clear_working' => true,
942                         'hook_extra' => array(
943                                 'theme' => $theme,
944                                 'type' => 'theme',
945                                 'action' => 'update',
946                         ),
947                 ) );
948
949                 remove_filter('upgrader_pre_install', array($this, 'current_before'));
950                 remove_filter('upgrader_post_install', array($this, 'current_after'));
951                 remove_filter('upgrader_clear_destination', array($this, 'delete_old_theme'));
952
953                 if ( ! $this->result || is_wp_error($this->result) )
954                         return $this->result;
955
956                 wp_clean_themes_cache( $parsed_args['clear_update_cache'] );
957
958                 return true;
959         }
960
961         function bulk_upgrade( $themes, $args = array() ) {
962
963                 $defaults = array(
964                         'clear_update_cache' => true,
965                 );
966                 $parsed_args = wp_parse_args( $args, $defaults );
967
968                 $this->init();
969                 $this->bulk = true;
970                 $this->upgrade_strings();
971
972                 $current = get_site_transient( 'update_themes' );
973
974                 add_filter('upgrader_pre_install', array($this, 'current_before'), 10, 2);
975                 add_filter('upgrader_post_install', array($this, 'current_after'), 10, 2);
976                 add_filter('upgrader_clear_destination', array($this, 'delete_old_theme'), 10, 4);
977
978                 $this->skin->header();
979
980                 // Connect to the Filesystem first.
981                 $res = $this->fs_connect( array(WP_CONTENT_DIR) );
982                 if ( ! $res ) {
983                         $this->skin->footer();
984                         return false;
985                 }
986
987                 $this->skin->bulk_header();
988
989                 // Only start maintenance mode if:
990                 // - running Multisite and there are one or more themes specified, OR
991                 // - a theme with an update available is currently in use.
992                 // @TODO: For multisite, maintenance mode should only kick in for individual sites if at all possible.
993                 $maintenance = ( is_multisite() && ! empty( $themes ) );
994                 foreach ( $themes as $theme )
995                         $maintenance = $maintenance || $theme == get_stylesheet() || $theme == get_template();
996                 if ( $maintenance )
997                         $this->maintenance_mode(true);
998
999                 $results = array();
1000
1001                 $this->update_count = count($themes);
1002                 $this->update_current = 0;
1003                 foreach ( $themes as $theme ) {
1004                         $this->update_current++;
1005
1006                         $this->skin->theme_info = $this->theme_info($theme);
1007
1008                         if ( !isset( $current->response[ $theme ] ) ) {
1009                                 $this->skin->set_result(true);
1010                                 $this->skin->before();
1011                                 $this->skin->feedback( 'up_to_date' );
1012                                 $this->skin->after();
1013                                 $results[$theme] = true;
1014                                 continue;
1015                         }
1016
1017                         // Get the URL to the zip file
1018                         $r = $current->response[ $theme ];
1019
1020                         $result = $this->run( array(
1021                                 'package' => $r['package'],
1022                                 'destination' => get_theme_root( $theme ),
1023                                 'clear_destination' => true,
1024                                 'clear_working' => true,
1025                                 'hook_extra' => array(
1026                                         'theme' => $theme
1027                                 ),
1028                         ) );
1029
1030                         $results[$theme] = $this->result;
1031
1032                         // Prevent credentials auth screen from displaying multiple times
1033                         if ( false === $result )
1034                                 break;
1035                 } //end foreach $plugins
1036
1037                 $this->maintenance_mode(false);
1038
1039                 /** This action is documented in wp-admin/includes/class-wp-upgrader.php */
1040                 do_action( 'upgrader_process_complete', $this, array(
1041                         'action' => 'update',
1042                         'type' => 'theme',
1043                         'bulk' => true,
1044                         'themes' => $themes,
1045                 ) );
1046
1047                 $this->skin->bulk_footer();
1048
1049                 $this->skin->footer();
1050
1051                 // Cleanup our hooks, in case something else does a upgrade on this connection.
1052                 remove_filter('upgrader_pre_install', array($this, 'current_before'));
1053                 remove_filter('upgrader_post_install', array($this, 'current_after'));
1054                 remove_filter('upgrader_clear_destination', array($this, 'delete_old_theme'));
1055
1056                 // Refresh the Theme Update information
1057                 wp_clean_themes_cache( $parsed_args['clear_update_cache'] );
1058
1059                 return $results;
1060         }
1061
1062         function check_package($source) {
1063                 global $wp_filesystem;
1064
1065                 if ( is_wp_error($source) )
1066                         return $source;
1067
1068                 // Check the folder contains a valid theme
1069                 $working_directory = str_replace( $wp_filesystem->wp_content_dir(), trailingslashit(WP_CONTENT_DIR), $source);
1070                 if ( ! is_dir($working_directory) ) // Sanity check, if the above fails, lets not prevent installation.
1071                         return $source;
1072
1073                 // A proper archive should have a style.css file in the single subdirectory
1074                 if ( ! file_exists( $working_directory . 'style.css' ) )
1075                         return new WP_Error( 'incompatible_archive_theme_no_style', $this->strings['incompatible_archive'], __( 'The theme is missing the <code>style.css</code> stylesheet.' ) );
1076
1077                 $info = get_file_data( $working_directory . 'style.css', array( 'Name' => 'Theme Name', 'Template' => 'Template' ) );
1078
1079                 if ( empty( $info['Name'] ) )
1080                         return new WP_Error( 'incompatible_archive_theme_no_name', $this->strings['incompatible_archive'], __( "The <code>style.css</code> stylesheet doesn't contain a valid theme header." ) );
1081
1082                 // If it's not a child theme, it must have at least an index.php to be legit.
1083                 if ( empty( $info['Template'] ) && ! file_exists( $working_directory . 'index.php' ) )
1084                         return new WP_Error( 'incompatible_archive_theme_no_index', $this->strings['incompatible_archive'], __( 'The theme is missing the <code>index.php</code> file.' ) );
1085
1086                 return $source;
1087         }
1088
1089         function current_before($return, $theme) {
1090
1091                 if ( is_wp_error($return) )
1092                         return $return;
1093
1094                 $theme = isset($theme['theme']) ? $theme['theme'] : '';
1095
1096                 if ( $theme != get_stylesheet() ) //If not current
1097                         return $return;
1098                 //Change to maintenance mode now.
1099                 if ( ! $this->bulk )
1100                         $this->maintenance_mode(true);
1101
1102                 return $return;
1103         }
1104
1105         function current_after($return, $theme) {
1106                 if ( is_wp_error($return) )
1107                         return $return;
1108
1109                 $theme = isset($theme['theme']) ? $theme['theme'] : '';
1110
1111                 if ( $theme != get_stylesheet() ) // If not current
1112                         return $return;
1113
1114                 // Ensure stylesheet name hasn't changed after the upgrade:
1115                 if ( $theme == get_stylesheet() && $theme != $this->result['destination_name'] ) {
1116                         wp_clean_themes_cache();
1117                         $stylesheet = $this->result['destination_name'];
1118                         switch_theme( $stylesheet );
1119                 }
1120
1121                 //Time to remove maintenance mode
1122                 if ( ! $this->bulk )
1123                         $this->maintenance_mode(false);
1124                 return $return;
1125         }
1126
1127         function delete_old_theme( $removed, $local_destination, $remote_destination, $theme ) {
1128                 global $wp_filesystem;
1129
1130                 if ( is_wp_error( $removed ) )
1131                         return $removed; // Pass errors through.
1132
1133                 if ( ! isset( $theme['theme'] ) )
1134                         return $removed;
1135
1136                 $theme = $theme['theme'];
1137                 $themes_dir = trailingslashit( $wp_filesystem->wp_themes_dir( $theme ) );
1138                 if ( $wp_filesystem->exists( $themes_dir . $theme ) ) {
1139                         if ( ! $wp_filesystem->delete( $themes_dir . $theme, true ) )
1140                                 return false;
1141                 }
1142
1143                 return true;
1144         }
1145
1146         function theme_info($theme = null) {
1147
1148                 if ( empty($theme) ) {
1149                         if ( !empty($this->result['destination_name']) )
1150                                 $theme = $this->result['destination_name'];
1151                         else
1152                                 return false;
1153                 }
1154                 return wp_get_theme( $theme );
1155         }
1156
1157 }
1158
1159 add_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 );
1160
1161 /**
1162  * Language pack upgrader, for updating translations of plugins, themes, and core.
1163  *
1164  * @package WordPress
1165  * @subpackage Upgrader
1166  * @since 3.7.0
1167  */
1168 class Language_Pack_Upgrader extends WP_Upgrader {
1169
1170         var $result;
1171         var $bulk = true;
1172
1173         static function async_upgrade( $upgrader = false ) {
1174                 // Avoid recursion.
1175                 if ( $upgrader && $upgrader instanceof Language_Pack_Upgrader )
1176                         return;
1177
1178                 // Nothing to do?
1179                 $language_updates = wp_get_translation_updates();
1180                 if ( ! $language_updates )
1181                         return;
1182
1183                 $skin = new Language_Pack_Upgrader_Skin( array(
1184                         'skip_header_footer' => true,
1185                 ) );
1186
1187                 $lp_upgrader = new Language_Pack_Upgrader( $skin );
1188                 $lp_upgrader->upgrade();
1189         }
1190
1191         function upgrade_strings() {
1192                 $this->strings['starting_upgrade'] = __( 'Some of your translations need updating. Sit tight for a few more seconds while we update them as well.' );
1193                 $this->strings['up_to_date'] = __( 'The translation is up to date.' ); // We need to silently skip this case
1194                 $this->strings['no_package'] = __( 'Update package not available.' );
1195                 $this->strings['downloading_package'] = __( 'Downloading translation from <span class="code">%s</span>&#8230;' );
1196                 $this->strings['unpack_package'] = __( 'Unpacking the update&#8230;' );
1197                 $this->strings['process_failed'] = __( 'Translation update failed.' );
1198                 $this->strings['process_success'] = __( 'Translation updated successfully.' );
1199         }
1200
1201         function upgrade( $update = false, $args = array() ) {
1202                 if ( $update )
1203                         $update = array( $update );
1204                 $results = $this->bulk_upgrade( $update, $args );
1205                 return $results[0];
1206         }
1207
1208         function bulk_upgrade( $language_updates = array(), $args = array() ) {
1209                 global $wp_filesystem;
1210
1211                 $defaults = array(
1212                         'clear_update_cache' => true,
1213                 );
1214                 $parsed_args = wp_parse_args( $args, $defaults );
1215
1216                 $this->init();
1217                 $this->upgrade_strings();
1218
1219                 if ( ! $language_updates )
1220                         $language_updates = wp_get_translation_updates();
1221
1222                 if ( empty( $language_updates ) ) {
1223                         $this->skin->header();
1224                         $this->skin->before();
1225                         $this->skin->set_result( true );
1226                         $this->skin->feedback( 'up_to_date' );
1227                         $this->skin->after();
1228                         $this->skin->bulk_footer();
1229                         $this->skin->footer();
1230                         return true;
1231                 }
1232
1233                 if ( 'upgrader_process_complete' == current_filter() )
1234                         $this->skin->feedback( 'starting_upgrade' );
1235
1236                 add_filter( 'upgrader_source_selection', array( &$this, 'check_package' ), 10, 3 );
1237
1238                 $this->skin->header();
1239
1240                 // Connect to the Filesystem first.
1241                 $res = $this->fs_connect( array( WP_CONTENT_DIR, WP_LANG_DIR ) );
1242                 if ( ! $res ) {
1243                         $this->skin->footer();
1244                         return false;
1245                 }
1246
1247                 $results = array();
1248
1249                 $this->update_count = count( $language_updates );
1250                 $this->update_current = 0;
1251
1252                 // The filesystem's mkdir() is not recursive. Make sure WP_LANG_DIR exists,
1253                 // as we then may need to create a /plugins or /themes directory inside of it.
1254                 $remote_destination = $wp_filesystem->find_folder( WP_LANG_DIR );
1255                 if ( ! $wp_filesystem->exists( $remote_destination ) )
1256                         if ( ! $wp_filesystem->mkdir( $remote_destination, FS_CHMOD_DIR ) )
1257                                 return new WP_Error( 'mkdir_failed_lang_dir', $this->strings['mkdir_failed'], $remote_destination );
1258
1259                 foreach ( $language_updates as $language_update ) {
1260
1261                         $this->skin->language_update = $language_update;
1262
1263                         $destination = WP_LANG_DIR;
1264                         if ( 'plugin' == $language_update->type )
1265                                 $destination .= '/plugins';
1266                         elseif ( 'theme' == $language_update->type )
1267                                 $destination .= '/themes';
1268
1269                         $this->update_current++;
1270
1271                         $options = array(
1272                                 'package' => $language_update->package,
1273                                 'destination' => $destination,
1274                                 'clear_destination' => false,
1275                                 'abort_if_destination_exists' => false, // We expect the destination to exist.
1276                                 'clear_working' => true,
1277                                 'is_multi' => true,
1278                                 'hook_extra' => array(
1279                                         'language_update_type' => $language_update->type,
1280                                         'language_update' => $language_update,
1281                                 )
1282                         );
1283
1284                         $result = $this->run( $options );
1285
1286                         $results[] = $this->result;
1287
1288                         // Prevent credentials auth screen from displaying multiple times.
1289                         if ( false === $result )
1290                                 break;
1291                 }
1292
1293                 $this->skin->bulk_footer();
1294
1295                 $this->skin->footer();
1296
1297                 // Clean up our hooks, in case something else does an upgrade on this connection.
1298                 remove_filter( 'upgrader_source_selection', array( &$this, 'check_package' ), 10, 2 );
1299
1300                 if ( $parsed_args['clear_update_cache'] ) {
1301                         wp_clean_themes_cache( true );
1302                         wp_clean_plugins_cache( true );
1303                         delete_site_transient( 'update_core' );
1304                 }
1305
1306                 return $results;
1307         }
1308
1309         function check_package( $source, $remote_source ) {
1310                 global $wp_filesystem;
1311
1312                 if ( is_wp_error( $source ) )
1313                         return $source;
1314
1315                 // Check that the folder contains a valid language.
1316                 $files = $wp_filesystem->dirlist( $remote_source );
1317
1318                 // Check to see if a .po and .mo exist in the folder.
1319                 $po = $mo = false;
1320                 foreach ( (array) $files as $file => $filedata ) {
1321                         if ( '.po' == substr( $file, -3 ) )
1322                                 $po = true;
1323                         elseif ( '.mo' == substr( $file, -3 ) )
1324                                 $mo = true;
1325                 }
1326
1327                 if ( ! $mo || ! $po )
1328                         return new WP_Error( 'incompatible_archive_pomo', $this->strings['incompatible_archive'],
1329                                 __( 'The language pack is missing either the <code>.po</code> or <code>.mo</code> files.' ) );
1330
1331                 return $source;
1332         }
1333
1334         function get_name_for_update( $update ) {
1335                 switch ( $update->type ) {
1336                         case 'core':
1337                                 return 'WordPress'; // Not translated
1338                                 break;
1339                         case 'theme':
1340                                 $theme = wp_get_theme( $update->slug );
1341                                 if ( $theme->exists() )
1342                                         return $theme->Get( 'Name' );
1343                                 break;
1344                         case 'plugin':
1345                                 $plugin_data = get_plugins( '/' . $update->slug );
1346                                 $plugin_data = array_shift( $plugin_data );
1347                                 if ( $plugin_data )
1348                                         return $plugin_data['Name'];
1349                                 break;
1350                 }
1351                 return '';
1352         }
1353
1354 }
1355
1356 /**
1357  * Core Upgrader class for WordPress. It allows for WordPress to upgrade itself in combination with the wp-admin/includes/update-core.php file
1358  *
1359  * @package WordPress
1360  * @subpackage Upgrader
1361  * @since 2.8.0
1362  */
1363 class Core_Upgrader extends WP_Upgrader {
1364
1365         function upgrade_strings() {
1366                 $this->strings['up_to_date'] = __('WordPress is at the latest version.');
1367                 $this->strings['no_package'] = __('Update package not available.');
1368                 $this->strings['downloading_package'] = __('Downloading update from <span class="code">%s</span>&#8230;');
1369                 $this->strings['unpack_package'] = __('Unpacking the update&#8230;');
1370                 $this->strings['copy_failed'] = __('Could not copy files.');
1371                 $this->strings['copy_failed_space'] = __('Could not copy files. You may have run out of disk space.' );
1372                 $this->strings['start_rollback'] = __( 'Attempting to roll back to previous version.' );
1373                 $this->strings['rollback_was_required'] = __( 'Due to an error during updating, WordPress has rolled back to your previous version.' );
1374         }
1375
1376         function upgrade( $current, $args = array() ) {
1377                 global $wp_filesystem;
1378
1379                 include ABSPATH . WPINC . '/version.php'; // $wp_version;
1380
1381                 $start_time = time();
1382
1383                 $defaults = array(
1384                         'pre_check_md5'    => true,
1385                         'attempt_rollback' => false,
1386                         'do_rollback'      => false,
1387                 );
1388                 $parsed_args = wp_parse_args( $args, $defaults );
1389
1390                 $this->init();
1391                 $this->upgrade_strings();
1392
1393                 // Is an update available?
1394                 if ( !isset( $current->response ) || $current->response == 'latest' )
1395                         return new WP_Error('up_to_date', $this->strings['up_to_date']);
1396
1397                 $res = $this->fs_connect( array(ABSPATH, WP_CONTENT_DIR) );
1398                 if ( ! $res || is_wp_error( $res ) ) {
1399                         return $res;
1400                 }
1401
1402                 $wp_dir = trailingslashit($wp_filesystem->abspath());
1403
1404                 $partial = true;
1405                 if ( $parsed_args['do_rollback'] )
1406                         $partial = false;
1407                 elseif ( $parsed_args['pre_check_md5'] && ! $this->check_files() )
1408                         $partial = false;
1409
1410                 /*
1411                  * If partial update is returned from the API, use that, unless we're doing
1412                  * a reinstall. If we cross the new_bundled version number, then use
1413                  * the new_bundled zip. Don't though if the constant is set to skip bundled items.
1414                  * If the API returns a no_content zip, go with it. Finally, default to the full zip.
1415                  */
1416                 if ( $parsed_args['do_rollback'] && $current->packages->rollback )
1417                         $to_download = 'rollback';
1418                 elseif ( $current->packages->partial && 'reinstall' != $current->response && $wp_version == $current->partial_version && $partial )
1419                         $to_download = 'partial';
1420                 elseif ( $current->packages->new_bundled && version_compare( $wp_version, $current->new_bundled, '<' )
1421                         && ( ! defined( 'CORE_UPGRADE_SKIP_NEW_BUNDLED' ) || ! CORE_UPGRADE_SKIP_NEW_BUNDLED ) )
1422                         $to_download = 'new_bundled';
1423                 elseif ( $current->packages->no_content )
1424                         $to_download = 'no_content';
1425                 else
1426                         $to_download = 'full';
1427
1428                 $download = $this->download_package( $current->packages->$to_download );
1429                 if ( is_wp_error($download) )
1430                         return $download;
1431
1432                 $working_dir = $this->unpack_package( $download );
1433                 if ( is_wp_error($working_dir) )
1434                         return $working_dir;
1435
1436                 // Copy update-core.php from the new version into place.
1437                 if ( !$wp_filesystem->copy($working_dir . '/wordpress/wp-admin/includes/update-core.php', $wp_dir . 'wp-admin/includes/update-core.php', true) ) {
1438                         $wp_filesystem->delete($working_dir, true);
1439                         return new WP_Error( 'copy_failed_for_update_core_file', __( 'The update cannot be installed because we will be unable to copy some files. This is usually due to inconsistent file permissions.' ), 'wp-admin/includes/update-core.php' );
1440                 }
1441                 $wp_filesystem->chmod($wp_dir . 'wp-admin/includes/update-core.php', FS_CHMOD_FILE);
1442
1443                 require_once( ABSPATH . 'wp-admin/includes/update-core.php' );
1444
1445                 if ( ! function_exists( 'update_core' ) )
1446                         return new WP_Error( 'copy_failed_space', $this->strings['copy_failed_space'] );
1447
1448                 $result = update_core( $working_dir, $wp_dir );
1449
1450                 // In the event of an issue, we may be able to roll back.
1451                 if ( $parsed_args['attempt_rollback'] && $current->packages->rollback && ! $parsed_args['do_rollback'] ) {
1452                         $try_rollback = false;
1453                         if ( is_wp_error( $result ) ) {
1454                                 $error_code = $result->get_error_code();
1455                                 // Not all errors are equal. These codes are critical: copy_failed__copy_dir,
1456                                 // mkdir_failed__copy_dir, copy_failed__copy_dir_retry, and disk_full.
1457                                 // do_rollback allows for update_core() to trigger a rollback if needed.
1458                                 if ( false !== strpos( $error_code, 'do_rollback' ) )
1459                                         $try_rollback = true;
1460                                 elseif ( false !== strpos( $error_code, '__copy_dir' ) )
1461                                         $try_rollback = true;
1462                                 elseif ( 'disk_full' === $error_code )
1463                                         $try_rollback = true;
1464                         }
1465
1466                         if ( $try_rollback ) {
1467                                 /** This filter is documented in wp-admin/includes/update-core.php */
1468                                 apply_filters( 'update_feedback', $result );
1469
1470                                 /** This filter is documented in wp-admin/includes/update-core.php */
1471                                 apply_filters( 'update_feedback', $this->strings['start_rollback'] );
1472
1473                                 $rollback_result = $this->upgrade( $current, array_merge( $parsed_args, array( 'do_rollback' => true ) ) );
1474
1475                                 $original_result = $result;
1476                                 $result = new WP_Error( 'rollback_was_required', $this->strings['rollback_was_required'], (object) array( 'update' => $original_result, 'rollback' => $rollback_result ) );
1477                         }
1478                 }
1479
1480                 /** This action is documented in wp-admin/includes/class-wp-upgrader.php */
1481                 do_action( 'upgrader_process_complete', $this, array( 'action' => 'update', 'type' => 'core' ) );
1482
1483                 // Clear the current updates
1484                 delete_site_transient( 'update_core' );
1485
1486                 if ( ! $parsed_args['do_rollback'] ) {
1487                         $stats = array(
1488                                 'update_type'      => $current->response,
1489                                 'success'          => true,
1490                                 'fs_method'        => $wp_filesystem->method,
1491                                 'fs_method_forced' => defined( 'FS_METHOD' ) || has_filter( 'filesystem_method' ),
1492                                 'time_taken'       => time() - $start_time,
1493                                 'reported'         => $wp_version,
1494                                 'attempted'        => $current->version,
1495                         );
1496
1497                         if ( is_wp_error( $result ) ) {
1498                                 $stats['success'] = false;
1499                                 // Did a rollback occur?
1500                                 if ( ! empty( $try_rollback ) ) {
1501                                         $stats['error_code'] = $original_result->get_error_code();
1502                                         $stats['error_data'] = $original_result->get_error_data();
1503                                         // Was the rollback successful? If not, collect its error too.
1504                                         $stats['rollback'] = ! is_wp_error( $rollback_result );
1505                                         if ( is_wp_error( $rollback_result ) ) {
1506                                                 $stats['rollback_code'] = $rollback_result->get_error_code();
1507                                                 $stats['rollback_data'] = $rollback_result->get_error_data();
1508                                         }
1509                                 } else {
1510                                         $stats['error_code'] = $result->get_error_code();
1511                                         $stats['error_data'] = $result->get_error_data();
1512                                 }
1513                         }
1514
1515                         wp_version_check( $stats );
1516                 }
1517
1518                 return $result;
1519         }
1520
1521         // Determines if this WordPress Core version should update to $offered_ver or not
1522         static function should_update_to_version( $offered_ver /* x.y.z */ ) {
1523                 include ABSPATH . WPINC . '/version.php'; // $wp_version; // x.y.z
1524
1525                 $current_branch = implode( '.', array_slice( preg_split( '/[.-]/', $wp_version  ), 0, 2 ) ); // x.y
1526                 $new_branch     = implode( '.', array_slice( preg_split( '/[.-]/', $offered_ver ), 0, 2 ) ); // x.y
1527                 $current_is_development_version = (bool) strpos( $wp_version, '-' );
1528
1529                 // Defaults:
1530                 $upgrade_dev   = true;
1531                 $upgrade_minor = true;
1532                 $upgrade_major = false;
1533
1534                 // WP_AUTO_UPDATE_CORE = true (all), 'minor', false.
1535                 if ( defined( 'WP_AUTO_UPDATE_CORE' ) ) {
1536                         if ( false === WP_AUTO_UPDATE_CORE ) {
1537                                 // Defaults to turned off, unless a filter allows it
1538                                 $upgrade_dev = $upgrade_minor = $upgrade_major = false;
1539                         } elseif ( true === WP_AUTO_UPDATE_CORE ) {
1540                                 // ALL updates for core
1541                                 $upgrade_dev = $upgrade_minor = $upgrade_major = true;
1542                         } elseif ( 'minor' === WP_AUTO_UPDATE_CORE ) {
1543                                 // Only minor updates for core
1544                                 $upgrade_dev = $upgrade_major = false;
1545                                 $upgrade_minor = true;
1546                         }
1547                 }
1548
1549                 // 1: If we're already on that version, not much point in updating?
1550                 if ( $offered_ver == $wp_version )
1551                         return false;
1552
1553                 // 2: If we're running a newer version, that's a nope
1554                 if ( version_compare( $wp_version, $offered_ver, '>' ) )
1555                         return false;
1556
1557                 $failure_data = get_site_option( 'auto_core_update_failed' );
1558                 if ( $failure_data ) {
1559                         // If this was a critical update failure, cannot update.
1560                         if ( ! empty( $failure_data['critical'] ) )
1561                                 return false;
1562
1563                         // Don't claim we can update on update-core.php if we have a non-critical failure logged.
1564                         if ( $wp_version == $failure_data['current'] && false !== strpos( $offered_ver, '.1.next.minor' ) )
1565                                 return false;
1566
1567                         // Cannot update if we're retrying the same A to B update that caused a non-critical failure.
1568                         // Some non-critical failures do allow retries, like download_failed.
1569                         // 3.7.1 => 3.7.2 resulted in files_not_writable, if we are still on 3.7.1 and still trying to update to 3.7.2.
1570                         if ( empty( $failure_data['retry'] ) && $wp_version == $failure_data['current'] && $offered_ver == $failure_data['attempted'] )
1571                                 return false;
1572                 }
1573
1574                 // 3: 3.7-alpha-25000 -> 3.7-alpha-25678 -> 3.7-beta1 -> 3.7-beta2
1575                 if ( $current_is_development_version ) {
1576
1577                         /**
1578                          * Filter whether to enable automatic core updates for development versions.
1579                          *
1580                          * @since 3.7.0
1581                          *
1582                          * @param bool $upgrade_dev Whether to enable automatic updates for
1583                          *                          development versions.
1584                          */
1585                         if ( ! apply_filters( 'allow_dev_auto_core_updates', $upgrade_dev ) )
1586                                 return false;
1587                         // else fall through to minor + major branches below
1588                 }
1589
1590                 // 4: Minor In-branch updates (3.7.0 -> 3.7.1 -> 3.7.2 -> 3.7.4)
1591                 if ( $current_branch == $new_branch ) {
1592
1593                         /**
1594                          * Filter whether to enable minor automatic core updates.
1595                          *
1596                          * @since 3.7.0
1597                          *
1598                          * @param bool $upgrade_minor Whether to enable minor automatic core updates.
1599                          */
1600                         return apply_filters( 'allow_minor_auto_core_updates', $upgrade_minor );
1601                 }
1602
1603                 // 5: Major version updates (3.7.0 -> 3.8.0 -> 3.9.1)
1604                 if ( version_compare( $new_branch, $current_branch, '>' ) ) {
1605
1606                         /**
1607                          * Filter whether to enable major automatic core updates.
1608                          *
1609                          * @since 3.7.0
1610                          *
1611                          * @param bool $upgrade_major Whether to enable major automatic core updates.
1612                          */
1613                         return apply_filters( 'allow_major_auto_core_updates', $upgrade_major );
1614                 }
1615
1616                 // If we're not sure, we don't want it
1617                 return false;
1618         }
1619
1620         function check_files() {
1621                 global $wp_version, $wp_local_package;
1622
1623                 $checksums = get_core_checksums( $wp_version, isset( $wp_local_package ) ? $wp_local_package : 'en_US' );
1624
1625                 if ( ! is_array( $checksums ) )
1626                         return false;
1627
1628                 foreach ( $checksums as $file => $checksum ) {
1629                         // Skip files which get updated
1630                         if ( 'wp-content' == substr( $file, 0, 10 ) )
1631                                 continue;
1632                         if ( ! file_exists( ABSPATH . $file ) || md5_file( ABSPATH . $file ) !== $checksum )
1633                                 return false;
1634                 }
1635
1636                 return true;
1637         }
1638 }
1639
1640 /**
1641  * Upgrade Skin helper for File uploads. This class handles the upload process and passes it as if it's a local file to the Upgrade/Installer functions.
1642  *
1643  * @package WordPress
1644  * @subpackage Upgrader
1645  * @since 2.8.0
1646  */
1647 class File_Upload_Upgrader {
1648         var $package;
1649         var $filename;
1650         var $id = 0;
1651
1652         function __construct($form, $urlholder) {
1653
1654                 if ( empty($_FILES[$form]['name']) && empty($_GET[$urlholder]) )
1655                         wp_die(__('Please select a file'));
1656
1657                 //Handle a newly uploaded file, Else assume it's already been uploaded
1658                 if ( ! empty($_FILES) ) {
1659                         $overrides = array( 'test_form' => false, 'test_type' => false );
1660                         $file = wp_handle_upload( $_FILES[$form], $overrides );
1661
1662                         if ( isset( $file['error'] ) )
1663                                 wp_die( $file['error'] );
1664
1665                         $this->filename = $_FILES[$form]['name'];
1666                         $this->package = $file['file'];
1667
1668                         // Construct the object array
1669                         $object = array(
1670                                 'post_title' => $this->filename,
1671                                 'post_content' => $file['url'],
1672                                 'post_mime_type' => $file['type'],
1673                                 'guid' => $file['url'],
1674                                 'context' => 'upgrader',
1675                                 'post_status' => 'private'
1676                         );
1677
1678                         // Save the data
1679                         $this->id = wp_insert_attachment( $object, $file['file'] );
1680
1681                         // schedule a cleanup for 2 hours from now in case of failed install
1682                         wp_schedule_single_event( time() + 7200, 'upgrader_scheduled_cleanup', array( $this->id ) );
1683
1684                 } elseif ( is_numeric( $_GET[$urlholder] ) ) {
1685                         // Numeric Package = previously uploaded file, see above.
1686                         $this->id = (int) $_GET[$urlholder];
1687                         $attachment = get_post( $this->id );
1688                         if ( empty($attachment) )
1689                                 wp_die(__('Please select a file'));
1690
1691                         $this->filename = $attachment->post_title;
1692                         $this->package = get_attached_file( $attachment->ID );
1693                 } else {
1694                         // Else, It's set to something, Back compat for plugins using the old (pre-3.3) File_Uploader handler.
1695                         if ( ! ( ( $uploads = wp_upload_dir() ) && false === $uploads['error'] ) )
1696                                 wp_die( $uploads['error'] );
1697
1698                         $this->filename = $_GET[$urlholder];
1699                         $this->package = $uploads['basedir'] . '/' . $this->filename;
1700                 }
1701         }
1702
1703         function cleanup() {
1704                 if ( $this->id )
1705                         wp_delete_attachment( $this->id );
1706
1707                 elseif ( file_exists( $this->package ) )
1708                         return @unlink( $this->package );
1709
1710                 return true;
1711         }
1712 }
1713
1714 /**
1715  * The WordPress automatic background updater.
1716  *
1717  * @package WordPress
1718  * @subpackage Upgrader
1719  * @since 3.7.0
1720  */
1721 class WP_Automatic_Updater {
1722
1723         /**
1724          * Tracks update results during processing.
1725          *
1726          * @var array
1727          */
1728         protected $update_results = array();
1729
1730         /**
1731          * Whether the entire automatic updater is disabled.
1732          *
1733          * @since 3.7.0
1734          */
1735         public function is_disabled() {
1736                 // Background updates are disabled if you don't want file changes.
1737                 if ( defined( 'DISALLOW_FILE_MODS' ) && DISALLOW_FILE_MODS )
1738                         return true;
1739
1740                 if ( defined( 'WP_INSTALLING' ) )
1741                         return true;
1742
1743                 // More fine grained control can be done through the WP_AUTO_UPDATE_CORE constant and filters.
1744                 $disabled = defined( 'AUTOMATIC_UPDATER_DISABLED' ) && AUTOMATIC_UPDATER_DISABLED;
1745
1746                 /**
1747                  * Filter whether to entirely disable background updates.
1748                  *
1749                  * There are more fine-grained filters and controls for selective disabling.
1750                  * This filter parallels the AUTOMATIC_UPDATER_DISABLED constant in name.
1751                  *
1752                  * This also disables update notification emails. That may change in the future.
1753                  *
1754                  * @since 3.7.0
1755                  *
1756                  * @param bool $disabled Whether the updater should be disabled.
1757                  */
1758                 return apply_filters( 'automatic_updater_disabled', $disabled );
1759         }
1760
1761         /**
1762          * Check for version control checkouts.
1763          *
1764          * Checks for Subversion, Git, Mercurial, and Bazaar. It recursively looks up the
1765          * filesystem to the top of the drive, erring on the side of detecting a VCS
1766          * checkout somewhere.
1767          *
1768          * ABSPATH is always checked in addition to whatever $context is (which may be the
1769          * wp-content directory, for example). The underlying assumption is that if you are
1770          * using version control *anywhere*, then you should be making decisions for
1771          * how things get updated.
1772          *
1773          * @since 3.7.0
1774          *
1775          * @param string $context The filesystem path to check, in addition to ABSPATH.
1776          */
1777         public function is_vcs_checkout( $context ) {
1778                 $context_dirs = array( untrailingslashit( $context ) );
1779                 if ( $context !== ABSPATH )
1780                         $context_dirs[] = untrailingslashit( ABSPATH );
1781
1782                 $vcs_dirs = array( '.svn', '.git', '.hg', '.bzr' );
1783                 $check_dirs = array();
1784
1785                 foreach ( $context_dirs as $context_dir ) {
1786                         // Walk up from $context_dir to the root.
1787                         do {
1788                                 $check_dirs[] = $context_dir;
1789
1790                                 // Once we've hit '/' or 'C:\', we need to stop. dirname will keep returning the input here.
1791                                 if ( $context_dir == dirname( $context_dir ) )
1792                                         break;
1793
1794                         // Continue one level at a time.
1795                         } while ( $context_dir = dirname( $context_dir ) );
1796                 }
1797
1798                 $check_dirs = array_unique( $check_dirs );
1799
1800                 // Search all directories we've found for evidence of version control.
1801                 foreach ( $vcs_dirs as $vcs_dir ) {
1802                         foreach ( $check_dirs as $check_dir ) {
1803                                 if ( $checkout = @is_dir( rtrim( $check_dir, '\\/' ) . "/$vcs_dir" ) )
1804                                         break 2;
1805                         }
1806                 }
1807
1808                 /**
1809                  * Filter whether the automatic updater should consider a filesystem
1810                  * location to be potentially managed by a version control system.
1811                  *
1812                  * @since 3.7.0
1813                  *
1814                  * @param bool $checkout  Whether a VCS checkout was discovered at $context
1815                  *                        or ABSPATH, or anywhere higher.
1816                  * @param string $context The filesystem context (a path) against which
1817                  *                        filesystem status should be checked.
1818                  */
1819                 return apply_filters( 'automatic_updates_is_vcs_checkout', $checkout, $context );
1820         }
1821
1822         /**
1823          * Tests to see if we can and should update a specific item.
1824          *
1825          * @since 3.7.0
1826          *
1827          * @param string $type    The type of update being checked: 'core', 'theme',
1828          *                        'plugin', 'translation'.
1829          * @param object $item    The update offer.
1830          * @param string $context The filesystem context (a path) against which filesystem
1831          *                        access and status should be checked.
1832          */
1833         public function should_update( $type, $item, $context ) {
1834                 // Used to see if WP_Filesystem is set up to allow unattended updates.
1835                 $skin = new Automatic_Upgrader_Skin;
1836
1837                 if ( $this->is_disabled() )
1838                         return false;
1839
1840                 // If we can't do an auto core update, we may still be able to email the user.
1841                 if ( ! $skin->request_filesystem_credentials( false, $context ) || $this->is_vcs_checkout( $context ) ) {
1842                         if ( 'core' == $type )
1843                                 $this->send_core_update_notification_email( $item );
1844                         return false;
1845                 }
1846
1847                 // Next up, is this an item we can update?
1848                 if ( 'core' == $type )
1849                         $update = Core_Upgrader::should_update_to_version( $item->current );
1850                 else
1851                         $update = ! empty( $item->autoupdate );
1852
1853                 /**
1854                  * Filter whether to automatically update core, a plugin, a theme, or a language.
1855                  *
1856                  * The dynamic portion of the hook name, $type, refers to the type of update
1857                  * being checked. Can be 'core', 'theme', 'plugin', or 'translation'.
1858                  *
1859                  * Generally speaking, plugins, themes, and major core versions are not updated
1860                  * by default, while translations and minor and development versions for core
1861                  * are updated by default.
1862                  *
1863                  * See the allow_dev_auto_core_updates, allow_minor_auto_core_updates, and
1864                  * allow_major_auto_core_updates filters for a more straightforward way to
1865                  * adjust core updates.
1866                  *
1867                  * @since 3.7.0
1868                  *
1869                  * @param bool   $update Whether to update.
1870                  * @param object $item   The update offer.
1871                  */
1872                 $update = apply_filters( 'auto_update_' . $type, $update, $item );
1873
1874                 if ( ! $update ) {
1875                         if ( 'core' == $type )
1876                                 $this->send_core_update_notification_email( $item );
1877                         return false;
1878                 }
1879
1880                 // If it's a core update, are we actually compatible with its requirements?
1881                 if ( 'core' == $type ) {
1882                         global $wpdb;
1883
1884                         $php_compat = version_compare( phpversion(), $item->php_version, '>=' );
1885                         if ( file_exists( WP_CONTENT_DIR . '/db.php' ) && empty( $wpdb->is_mysql ) )
1886                                 $mysql_compat = true;
1887                         else
1888                                 $mysql_compat = version_compare( $wpdb->db_version(), $item->mysql_version, '>=' );
1889
1890                         if ( ! $php_compat || ! $mysql_compat )
1891                                 return false;
1892                 }
1893
1894                 return true;
1895         }
1896
1897         /**
1898          * Notifies an administrator of a core update.
1899          *
1900          * @since 3.7.0
1901          *
1902          * @param object $item The update offer.
1903          */
1904         protected function send_core_update_notification_email( $item ) {
1905                 $notify   = true;
1906                 $notified = get_site_option( 'auto_core_update_notified' );
1907
1908                 // Don't notify if we've already notified the same email address of the same version.
1909                 if ( $notified && $notified['email'] == get_site_option( 'admin_email' ) && $notified['version'] == $item->current )
1910                         return false;
1911
1912                 // See if we need to notify users of a core update.
1913                 $notify = ! empty( $item->notify_email );
1914
1915                 /**
1916                  * Filter whether to notify the site administrator of a new core update.
1917                  *
1918                  * By default, administrators are notified when the update offer received
1919                  * from WordPress.org sets a particular flag. This allows some discretion
1920                  * in if and when to notify.
1921                  *
1922                  * This filter is only evaluated once per release. If the same email address
1923                  * was already notified of the same new version, WordPress won't repeatedly
1924                  * email the administrator.
1925                  *
1926                  * This filter is also used on about.php to check if a plugin has disabled
1927                  * these notifications.
1928                  *
1929                  * @since 3.7.0
1930                  *
1931                  * @param bool   $notify Whether the site administrator is notified.
1932                  * @param object $item   The update offer.
1933                  */
1934                 if ( ! apply_filters( 'send_core_update_notification_email', $notify, $item ) )
1935                         return false;
1936
1937                 $this->send_email( 'manual', $item );
1938                 return true;
1939         }
1940
1941         /**
1942          * Update an item, if appropriate.
1943          *
1944          * @since 3.7.0
1945          *
1946          * @param string $type The type of update being checked: 'core', 'theme', 'plugin', 'translation'.
1947          * @param object $item The update offer.
1948          */
1949         public function update( $type, $item ) {
1950                 $skin = new Automatic_Upgrader_Skin;
1951
1952                 switch ( $type ) {
1953                         case 'core':
1954                                 // The Core upgrader doesn't use the Upgrader's skin during the actual main part of the upgrade, instead, firing a filter.
1955                                 add_filter( 'update_feedback', array( $skin, 'feedback' ) );
1956                                 $upgrader = new Core_Upgrader( $skin );
1957                                 $context  = ABSPATH;
1958                                 break;
1959                         case 'plugin':
1960                                 $upgrader = new Plugin_Upgrader( $skin );
1961                                 $context  = WP_PLUGIN_DIR; // We don't support custom Plugin directories, or updates for WPMU_PLUGIN_DIR
1962                                 break;
1963                         case 'theme':
1964                                 $upgrader = new Theme_Upgrader( $skin );
1965                                 $context  = get_theme_root( $item->theme );
1966                                 break;
1967                         case 'translation':
1968                                 $upgrader = new Language_Pack_Upgrader( $skin );
1969                                 $context  = WP_CONTENT_DIR; // WP_LANG_DIR;
1970                                 break;
1971                 }
1972
1973                 // Determine whether we can and should perform this update.
1974                 if ( ! $this->should_update( $type, $item, $context ) )
1975                         return false;
1976
1977                 $upgrader_item = $item;
1978                 switch ( $type ) {
1979                         case 'core':
1980                                 $skin->feedback( __( 'Updating to WordPress %s' ), $item->version );
1981                                 $item_name = sprintf( __( 'WordPress %s' ), $item->version );
1982                                 break;
1983                         case 'theme':
1984                                 $upgrader_item = $item->theme;
1985                                 $theme = wp_get_theme( $upgrader_item );
1986                                 $item_name = $theme->Get( 'Name' );
1987                                 $skin->feedback( __( 'Updating theme: %s' ), $item_name );
1988                                 break;
1989                         case 'plugin':
1990                                 $upgrader_item = $item->plugin;
1991                                 $plugin_data = get_plugin_data( $context . '/' . $upgrader_item );
1992                                 $item_name = $plugin_data['Name'];
1993                                 $skin->feedback( __( 'Updating plugin: %s' ), $item_name );
1994                                 break;
1995                         case 'translation':
1996                                 $language_item_name = $upgrader->get_name_for_update( $item );
1997                                 $item_name = sprintf( __( 'Translations for %s' ), $language_item_name );
1998                                 $skin->feedback( sprintf( __( 'Updating translations for %1$s (%2$s)&#8230;' ), $language_item_name, $item->language ) );
1999                                 break;
2000                 }
2001
2002                 // Boom, This sites about to get a whole new splash of paint!
2003                 $upgrade_result = $upgrader->upgrade( $upgrader_item, array(
2004                         'clear_update_cache' => false,
2005                         'pre_check_md5'      => false, /* always use partial builds if possible for core updates */
2006                         'attempt_rollback'   => true, /* only available for core updates */
2007                 ) );
2008
2009                 // if the filesystem is unavailable, false is returned.
2010                 if ( false === $upgrade_result ) {
2011                         $upgrade_result = new WP_Error( 'fs_unavailable', __( 'Could not access filesystem.' ) );
2012                 }
2013
2014                 // Core doesn't output this, so lets append it so we don't get confused
2015                 if ( 'core' == $type ) {
2016                         if ( is_wp_error( $upgrade_result ) ) {
2017                                 $skin->error( __( 'Installation Failed' ), $upgrade_result );
2018                         } else {
2019                                 $skin->feedback( __( 'WordPress updated successfully' ) );
2020                         }
2021                 }
2022
2023                 $this->update_results[ $type ][] = (object) array(
2024                         'item'     => $item,
2025                         'result'   => $upgrade_result,
2026                         'name'     => $item_name,
2027                         'messages' => $skin->get_upgrade_messages()
2028                 );
2029
2030                 return $upgrade_result;
2031         }
2032
2033         /**
2034          * Kicks off the background update process, looping through all pending updates.
2035          *
2036          * @since 3.7.0
2037          */
2038         public function run() {
2039                 global $wpdb, $wp_version;
2040
2041                 if ( $this->is_disabled() )
2042                         return;
2043
2044                 if ( ! is_main_network() || ! is_main_site() )
2045                         return;
2046
2047                 $lock_name = 'auto_updater.lock';
2048
2049                 // Try to lock
2050                 $lock_result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'no') /* LOCK */", $lock_name, time() ) );
2051
2052                 if ( ! $lock_result ) {
2053                         $lock_result = get_option( $lock_name );
2054
2055                         // If we couldn't create a lock, and there isn't a lock, bail
2056                         if ( ! $lock_result )
2057                                 return;
2058
2059                         // Check to see if the lock is still valid
2060                         if ( $lock_result > ( time() - HOUR_IN_SECONDS ) )
2061                                 return;
2062                 }
2063
2064                 // Update the lock, as by this point we've definately got a lock, just need to fire the actions
2065                 update_option( $lock_name, time() );
2066
2067                 // Don't automatically run these thins, as we'll handle it ourselves
2068                 remove_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 );
2069                 remove_action( 'upgrader_process_complete', 'wp_version_check' );
2070                 remove_action( 'upgrader_process_complete', 'wp_update_plugins' );
2071                 remove_action( 'upgrader_process_complete', 'wp_update_themes' );
2072
2073                 // Next, Plugins
2074                 wp_update_plugins(); // Check for Plugin updates
2075                 $plugin_updates = get_site_transient( 'update_plugins' );
2076                 if ( $plugin_updates && !empty( $plugin_updates->response ) ) {
2077                         foreach ( $plugin_updates->response as $plugin ) {
2078                                 $this->update( 'plugin', $plugin );
2079                         }
2080                         // Force refresh of plugin update information
2081                         wp_clean_plugins_cache();
2082                 }
2083
2084                 // Next, those themes we all love
2085                 wp_update_themes();  // Check for Theme updates
2086                 $theme_updates = get_site_transient( 'update_themes' );
2087                 if ( $theme_updates && !empty( $theme_updates->response ) ) {
2088                         foreach ( $theme_updates->response as $theme ) {
2089                                 $this->update( 'theme', (object) $theme );
2090                         }
2091                         // Force refresh of theme update information
2092                         wp_clean_themes_cache();
2093                 }
2094
2095                 // Next, Process any core update
2096                 wp_version_check(); // Check for Core updates
2097                 $core_update = find_core_auto_update();
2098
2099                 if ( $core_update )
2100                         $this->update( 'core', $core_update );
2101
2102                 // Clean up, and check for any pending translations
2103                 // (Core_Upgrader checks for core updates)
2104                 $theme_stats = array();
2105                 if ( isset( $this->update_results['theme'] ) ) {
2106                         foreach ( $this->update_results['theme'] as $upgrade ) {
2107                                 $theme_stats[ $upgrade->item->theme ] = ( true === $upgrade->result );
2108                         }
2109                 }
2110                 wp_update_themes( $theme_stats );  // Check for Theme updates
2111
2112                 $plugin_stats = array();
2113                 if ( isset( $this->update_results['plugin'] ) ) {
2114                         foreach ( $this->update_results['plugin'] as $upgrade ) {
2115                                 $plugin_stats[ $upgrade->item->plugin ] = ( true === $upgrade->result );
2116                         }
2117                 }
2118                 wp_update_plugins( $plugin_stats ); // Check for Plugin updates
2119
2120                 // Finally, Process any new translations
2121                 $language_updates = wp_get_translation_updates();
2122                 if ( $language_updates ) {
2123                         foreach ( $language_updates as $update ) {
2124                                 $this->update( 'translation', $update );
2125                         }
2126
2127                         // Clear existing caches
2128                         wp_clean_plugins_cache();
2129                         wp_clean_themes_cache();
2130                         delete_site_transient( 'update_core' );
2131
2132                         wp_version_check();  // check for Core updates
2133                         wp_update_themes();  // Check for Theme updates
2134                         wp_update_plugins(); // Check for Plugin updates
2135                 }
2136
2137                 // Send debugging email to all development installs.
2138                 if ( ! empty( $this->update_results ) ) {
2139                         $development_version = false !== strpos( $wp_version, '-' );
2140
2141                         /**
2142                          * Filter whether to send a debugging email for each automatic background update.
2143                          *
2144                          * @since 3.7.0
2145                          *
2146                          * @param bool $development_version By default, emails are sent if the
2147                          *                                  install is a development version.
2148                          *                                  Return false to avoid the email.
2149                          */
2150                         if ( apply_filters( 'automatic_updates_send_debug_email', $development_version ) )
2151                                 $this->send_debug_email();
2152
2153                         if ( ! empty( $this->update_results['core'] ) )
2154                                 $this->after_core_update( $this->update_results['core'][0] );
2155
2156                         /**
2157                          * Fires after all automatic updates have run.
2158                          *
2159                          * @since 3.8.0
2160                          *
2161                          * @param array $update_results The results of all attempted updates.
2162                          */
2163                         do_action( 'automatic_updates_complete', $this->update_results );
2164                 }
2165
2166                 // Clear the lock
2167                 delete_option( $lock_name );
2168         }
2169
2170         /**
2171          * If we tried to perform a core update, check if we should send an email,
2172          * and if we need to avoid processing future updates.
2173          *
2174          * @param object $update_result The result of the core update. Includes the update offer and result.
2175          */
2176         protected function after_core_update( $update_result ) {
2177                 global $wp_version;
2178
2179                 $core_update = $update_result->item;
2180                 $result      = $update_result->result;
2181
2182                 if ( ! is_wp_error( $result ) ) {
2183                         $this->send_email( 'success', $core_update );
2184                         return;
2185                 }
2186
2187                 $error_code = $result->get_error_code();
2188
2189                 // Any of these WP_Error codes are critical failures, as in they occurred after we started to copy core files.
2190                 // We should not try to perform a background update again until there is a successful one-click update performed by the user.
2191                 $critical = false;
2192                 if ( $error_code === 'disk_full' || false !== strpos( $error_code, '__copy_dir' ) ) {
2193                         $critical = true;
2194                 } elseif ( $error_code === 'rollback_was_required' && is_wp_error( $result->get_error_data()->rollback ) ) {
2195                         // A rollback is only critical if it failed too.
2196                         $critical = true;
2197                         $rollback_result = $result->get_error_data()->rollback;
2198                 } elseif ( false !== strpos( $error_code, 'do_rollback' ) ) {
2199                         $critical = true;
2200                 }
2201
2202                 if ( $critical ) {
2203                         $critical_data = array(
2204                                 'attempted'  => $core_update->current,
2205                                 'current'    => $wp_version,
2206                                 'error_code' => $error_code,
2207                                 'error_data' => $result->get_error_data(),
2208                                 'timestamp'  => time(),
2209                                 'critical'   => true,
2210                         );
2211                         if ( isset( $rollback_result ) ) {
2212                                 $critical_data['rollback_code'] = $rollback_result->get_error_code();
2213                                 $critical_data['rollback_data'] = $rollback_result->get_error_data();
2214                         }
2215                         update_site_option( 'auto_core_update_failed', $critical_data );
2216                         $this->send_email( 'critical', $core_update, $result );
2217                         return;
2218                 }
2219
2220                 /*
2221                  * Any other WP_Error code (like download_failed or files_not_writable) occurs before
2222                  * we tried to copy over core files. Thus, the failures are early and graceful.
2223                  *
2224                  * We should avoid trying to perform a background update again for the same version.
2225                  * But we can try again if another version is released.
2226                  *
2227                  * For certain 'transient' failures, like download_failed, we should allow retries.
2228                  * In fact, let's schedule a special update for an hour from now. (It's possible
2229                  * the issue could actually be on WordPress.org's side.) If that one fails, then email.
2230                  */
2231                 $send = true;
2232                 $transient_failures = array( 'incompatible_archive', 'download_failed', 'insane_distro' );
2233                 if ( in_array( $error_code, $transient_failures ) && ! get_site_option( 'auto_core_update_failed' ) ) {
2234                         wp_schedule_single_event( time() + HOUR_IN_SECONDS, 'wp_maybe_auto_update' );
2235                         $send = false;
2236                 }
2237
2238                 $n = get_site_option( 'auto_core_update_notified' );
2239                 // Don't notify if we've already notified the same email address of the same version of the same notification type.
2240                 if ( $n && 'fail' == $n['type'] && $n['email'] == get_site_option( 'admin_email' ) && $n['version'] == $core_update->current )
2241                         $send = false;
2242
2243                 update_site_option( 'auto_core_update_failed', array(
2244                         'attempted'  => $core_update->current,
2245                         'current'    => $wp_version,
2246                         'error_code' => $error_code,
2247                         'error_data' => $result->get_error_data(),
2248                         'timestamp'  => time(),
2249                         'retry'      => in_array( $error_code, $transient_failures ),
2250                 ) );
2251
2252                 if ( $send )
2253                         $this->send_email( 'fail', $core_update, $result );
2254         }
2255
2256         /**
2257          * Sends an email upon the completion or failure of a background core update.
2258          *
2259          * @since 3.7.0
2260          *
2261          * @param string $type        The type of email to send. Can be one of 'success', 'fail', 'manual', 'critical'.
2262          * @param object $core_update The update offer that was attempted.
2263          * @param mixed  $result      Optional. The result for the core update. Can be WP_Error.
2264          */
2265         protected function send_email( $type, $core_update, $result = null ) {
2266                 update_site_option( 'auto_core_update_notified', array(
2267                         'type'      => $type,
2268                         'email'     => get_site_option( 'admin_email' ),
2269                         'version'   => $core_update->current,
2270                         'timestamp' => time(),
2271                 ) );
2272
2273                 $next_user_core_update = get_preferred_from_update_core();
2274                 // If the update transient is empty, use the update we just performed
2275                 if ( ! $next_user_core_update )
2276                         $next_user_core_update = $core_update;
2277                 $newer_version_available = ( 'upgrade' == $next_user_core_update->response && version_compare( $next_user_core_update->version, $core_update->version, '>' ) );
2278
2279                 /**
2280                  * Filter whether to send an email following an automatic background core update.
2281                  *
2282                  * @since 3.7.0
2283                  *
2284                  * @param bool   $send        Whether to send the email. Default true.
2285                  * @param string $type        The type of email to send. Can be one of
2286                  *                            'success', 'fail', 'critical'.
2287                  * @param object $core_update The update offer that was attempted.
2288                  * @param mixed  $result      The result for the core update. Can be WP_Error.
2289                  */
2290                 if ( 'manual' !== $type && ! apply_filters( 'auto_core_update_send_email', true, $type, $core_update, $result ) )
2291                         return;
2292
2293                 switch ( $type ) {
2294                         case 'success' : // We updated.
2295                                 /* translators: 1: Site name, 2: WordPress version number. */
2296                                 $subject = __( '[%1$s] Your site has updated to WordPress %2$s' );
2297                                 break;
2298
2299                         case 'fail' :   // We tried to update but couldn't.
2300                         case 'manual' : // We can't update (and made no attempt).
2301                                 /* translators: 1: Site name, 2: WordPress version number. */
2302                                 $subject = __( '[%1$s] WordPress %2$s is available. Please update!' );
2303                                 break;
2304
2305                         case 'critical' : // We tried to update, started to copy files, then things went wrong.
2306                                 /* translators: 1: Site name. */
2307                                 $subject = __( '[%1$s] URGENT: Your site may be down due to a failed update' );
2308                                 break;
2309
2310                         default :
2311                                 return;
2312                 }
2313
2314                 // If the auto update is not to the latest version, say that the current version of WP is available instead.
2315                 $version = 'success' === $type ? $core_update->current : $next_user_core_update->current;
2316                 $subject = sprintf( $subject, wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ), $version );
2317
2318                 $body = '';
2319
2320                 switch ( $type ) {
2321                         case 'success' :
2322                                 $body .= sprintf( __( 'Howdy! Your site at %1$s has been updated automatically to WordPress %2$s.' ), home_url(), $core_update->current );
2323                                 $body .= "\n\n";
2324                                 if ( ! $newer_version_available )
2325                                         $body .= __( 'No further action is needed on your part.' ) . ' ';
2326
2327                                 // Can only reference the About screen if their update was successful.
2328                                 list( $about_version ) = explode( '-', $core_update->current, 2 );
2329                                 $body .= sprintf( __( "For more on version %s, see the About WordPress screen:" ), $about_version );
2330                                 $body .= "\n" . admin_url( 'about.php' );
2331
2332                                 if ( $newer_version_available ) {
2333                                         $body .= "\n\n" . sprintf( __( 'WordPress %s is also now available.' ), $next_user_core_update->current ) . ' ';
2334                                         $body .= __( 'Updating is easy and only takes a few moments:' );
2335                                         $body .= "\n" . network_admin_url( 'update-core.php' );
2336                                 }
2337
2338                                 break;
2339
2340                         case 'fail' :
2341                         case 'manual' :
2342                                 $body .= sprintf( __( 'Please update your site at %1$s to WordPress %2$s.' ), home_url(), $next_user_core_update->current );
2343
2344                                 $body .= "\n\n";
2345
2346                                 // Don't show this message if there is a newer version available.
2347                                 // Potential for confusion, and also not useful for them to know at this point.
2348                                 if ( 'fail' == $type && ! $newer_version_available )
2349                                         $body .= __( 'We tried but were unable to update your site automatically.' ) . ' ';
2350
2351                                 $body .= __( 'Updating is easy and only takes a few moments:' );
2352                                 $body .= "\n" . network_admin_url( 'update-core.php' );
2353                                 break;
2354
2355                         case 'critical' :
2356                                 if ( $newer_version_available )
2357                                         $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 );
2358                                 else
2359                                         $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 );
2360
2361                                 $body .= "\n\n" . __( "This means your site may be offline or broken. Don't panic; this can be fixed." );
2362
2363                                 $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:" );
2364                                 $body .= "\n" . network_admin_url( 'update-core.php' );
2365                                 break;
2366                 }
2367
2368                 $critical_support = 'critical' === $type && ! empty( $core_update->support_email );
2369                 if ( $critical_support ) {
2370                         // Support offer if available.
2371                         $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 );
2372                 } else {
2373                         // Add a note about the support forums.
2374                         $body .= "\n\n" . __( 'If you experience any issues or need support, the volunteers in the WordPress.org support forums may be able to help.' );
2375                         $body .= "\n" . __( 'https://wordpress.org/support/' );
2376                 }
2377
2378                 // Updates are important!
2379                 if ( $type != 'success' || $newer_version_available ) {
2380                         $body .= "\n\n" . __( 'Keeping your site updated is important for security. It also makes the internet a safer place for you and your readers.' );
2381                 }
2382
2383                 if ( $critical_support ) {
2384                         $body .= " " . __( "If you reach out to us, we'll also ensure you'll never have this problem again." );
2385                 }
2386
2387                 // If things are successful and we're now on the latest, mention plugins and themes if any are out of date.
2388                 if ( $type == 'success' && ! $newer_version_available && ( get_plugin_updates() || get_theme_updates() ) ) {
2389                         $body .= "\n\n" . __( 'You also have some plugins or themes with updates available. Update them now:' );
2390                         $body .= "\n" . network_admin_url();
2391                 }
2392
2393                 $body .= "\n\n" . __( 'The WordPress Team' ) . "\n";
2394
2395                 if ( 'critical' == $type && is_wp_error( $result ) ) {
2396                         $body .= "\n***\n\n";
2397                         $body .= sprintf( __( 'Your site was running version %s.' ), $GLOBALS['wp_version'] );
2398                         $body .= ' ' . __( 'We have some data that describes the error your site encountered.' );
2399                         $body .= ' ' . __( 'Your hosting company, support forum volunteers, or a friendly developer may be able to use this information to help you:' );
2400
2401                         // If we had a rollback and we're still critical, then the rollback failed too.
2402                         // Loop through all errors (the main WP_Error, the update result, the rollback result) for code, data, etc.
2403                         if ( 'rollback_was_required' == $result->get_error_code() )
2404                                 $errors = array( $result, $result->get_error_data()->update, $result->get_error_data()->rollback );
2405                         else
2406                                 $errors = array( $result );
2407
2408                         foreach ( $errors as $error ) {
2409                                 if ( ! is_wp_error( $error ) )
2410                                         continue;
2411                                 $error_code = $error->get_error_code();
2412                                 $body .= "\n\n" . sprintf( __( "Error code: %s" ), $error_code );
2413                                 if ( 'rollback_was_required' == $error_code )
2414                                         continue;
2415                                 if ( $error->get_error_message() )
2416                                         $body .= "\n" . $error->get_error_message();
2417                                 $error_data = $error->get_error_data();
2418                                 if ( $error_data )
2419                                         $body .= "\n" . implode( ', ', (array) $error_data );
2420                         }
2421                         $body .= "\n";
2422                 }
2423
2424                 $to  = get_site_option( 'admin_email' );
2425                 $headers = '';
2426
2427                 $email = compact( 'to', 'subject', 'body', 'headers' );
2428
2429                 /**
2430                  * Filter the email sent following an automatic background core update.
2431                  *
2432                  * @since 3.7.0
2433                  *
2434                  * @param array $email {
2435                  *     Array of email arguments that will be passed to wp_mail().
2436                  *
2437                  *     @type string $to      The email recipient. An array of emails
2438                  *                            can be returned, as handled by wp_mail().
2439                  *     @type string $subject The email's subject.
2440                  *     @type string $body    The email message body.
2441                  *     @type string $headers Any email headers, defaults to no headers.
2442                  * }
2443                  * @param string $type        The type of email being sent. Can be one of
2444                  *                            'success', 'fail', 'manual', 'critical'.
2445                  * @param object $core_update The update offer that was attempted.
2446                  * @param mixed  $result      The result for the core update. Can be WP_Error.
2447                  */
2448                 $email = apply_filters( 'auto_core_update_email', $email, $type, $core_update, $result );
2449
2450                 wp_mail( $email['to'], wp_specialchars_decode( $email['subject'] ), $email['body'], $email['headers'] );
2451         }
2452
2453         /**
2454          * Prepares and sends an email of a full log of background update results, useful for debugging and geekery.
2455          *
2456          * @since 3.7.0
2457          */
2458         protected function send_debug_email() {
2459                 $update_count = 0;
2460                 foreach ( $this->update_results as $type => $updates )
2461                         $update_count += count( $updates );
2462
2463                 $body = array();
2464                 $failures = 0;
2465
2466                 $body[] = sprintf( __( 'WordPress site: %s' ), network_home_url( '/' ) );
2467
2468                 // Core
2469                 if ( isset( $this->update_results['core'] ) ) {
2470                         $result = $this->update_results['core'][0];
2471                         if ( $result->result && ! is_wp_error( $result->result ) ) {
2472                                 $body[] = sprintf( __( 'SUCCESS: WordPress was successfully updated to %s' ), $result->name );
2473                         } else {
2474                                 $body[] = sprintf( __( 'FAILED: WordPress failed to update to %s' ), $result->name );
2475                                 $failures++;
2476                         }
2477                         $body[] = '';
2478                 }
2479
2480                 // Plugins, Themes, Translations
2481                 foreach ( array( 'plugin', 'theme', 'translation' ) as $type ) {
2482                         if ( ! isset( $this->update_results[ $type ] ) )
2483                                 continue;
2484                         $success_items = wp_list_filter( $this->update_results[ $type ], array( 'result' => true ) );
2485                         if ( $success_items ) {
2486                                 $messages = array(
2487                                         'plugin'      => __( 'The following plugins were successfully updated:' ),
2488                                         'theme'       => __( 'The following themes were successfully updated:' ),
2489                                         'translation' => __( 'The following translations were successfully updated:' ),
2490                                 );
2491
2492                                 $body[] = $messages[ $type ];
2493                                 foreach ( wp_list_pluck( $success_items, 'name' ) as $name ) {
2494                                         $body[] = ' * ' . sprintf( __( 'SUCCESS: %s' ), $name );
2495                                 }
2496                         }
2497                         if ( $success_items != $this->update_results[ $type ] ) {
2498                                 // Failed updates
2499                                 $messages = array(
2500                                         'plugin'      => __( 'The following plugins failed to update:' ),
2501                                         'theme'       => __( 'The following themes failed to update:' ),
2502                                         'translation' => __( 'The following translations failed to update:' ),
2503                                 );
2504
2505                                 $body[] = $messages[ $type ];
2506                                 foreach ( $this->update_results[ $type ] as $item ) {
2507                                         if ( ! $item->result || is_wp_error( $item->result ) ) {
2508                                                 $body[] = ' * ' . sprintf( __( 'FAILED: %s' ), $item->name );
2509                                                 $failures++;
2510                                         }
2511                                 }
2512                         }
2513                         $body[] = '';
2514                 }
2515
2516                 $site_title = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );
2517                 if ( $failures ) {
2518                         $body[] = __( "
2519 BETA TESTING?
2520 =============
2521
2522 This debugging email is sent when you are using a development version of WordPress.
2523
2524 If you think these failures might be due to a bug in WordPress, could you report it?
2525  * Open a thread in the support forums: https://wordpress.org/support/forum/alphabeta
2526  * Or, if you're comfortable writing a bug report: http://core.trac.wordpress.org/
2527
2528 Thanks! -- The WordPress Team" );
2529
2530                         $subject = sprintf( __( '[%s] There were failures during background updates' ), $site_title );
2531                 } else {
2532                         $subject = sprintf( __( '[%s] Background updates have finished' ), $site_title );
2533                 }
2534
2535                 $title = __( 'UPDATE LOG' );
2536                 $body[] = $title;
2537                 $body[] = str_repeat( '=', strlen( $title ) );
2538                 $body[] = '';
2539
2540                 foreach ( array( 'core', 'plugin', 'theme', 'translation' ) as $type ) {
2541                         if ( ! isset( $this->update_results[ $type ] ) )
2542                                 continue;
2543                         foreach ( $this->update_results[ $type ] as $update ) {
2544                                 $body[] = $update->name;
2545                                 $body[] = str_repeat( '-', strlen( $update->name ) );
2546                                 foreach ( $update->messages as $message )
2547                                         $body[] = "  " . html_entity_decode( str_replace( '&#8230;', '...', $message ) );
2548                                 if ( is_wp_error( $update->result ) ) {
2549                                         $results = array( 'update' => $update->result );
2550                                         // If we rolled back, we want to know an error that occurred then too.
2551                                         if ( 'rollback_was_required' === $update->result->get_error_code() )
2552                                                 $results = (array) $update->result->get_error_data();
2553                                         foreach ( $results as $result_type => $result ) {
2554                                                 if ( ! is_wp_error( $result ) )
2555                                                         continue;
2556
2557                                                 if ( 'rollback' === $result_type ) {
2558                                                         /* translators: 1: Error code, 2: Error message. */
2559                                                         $body[] = '  ' . sprintf( __( 'Rollback Error: [%1$s] %2$s' ), $result->get_error_code(), $result->get_error_message() );
2560                                                 } else {
2561                                                         /* translators: 1: Error code, 2: Error message. */
2562                                                         $body[] = '  ' . sprintf( __( 'Error: [%1$s] %2$s' ), $result->get_error_code(), $result->get_error_message() );
2563                                                 }
2564
2565                                                 if ( $result->get_error_data() )
2566                                                         $body[] = '         ' . implode( ', ', (array) $result->get_error_data() );
2567                                         }
2568                                 }
2569                                 $body[] = '';
2570                         }
2571                 }
2572
2573                 $email = array(
2574                         'to'      => get_site_option( 'admin_email' ),
2575                         'subject' => $subject,
2576                         'body'    => implode( "\n", $body ),
2577                         'headers' => ''
2578                 );
2579
2580                 /**
2581                  * Filter the debug email that can be sent following an automatic
2582                  * background core update.
2583                  *
2584                  * @since 3.8.0
2585                  *
2586                  * @param array $email {
2587                  *     Array of email arguments that will be passed to wp_mail().
2588                  *
2589                  *     @type string $to      The email recipient. An array of emails
2590                  *                           can be returned, as handled by wp_mail().
2591                  *     @type string $subject Email subject.
2592                  *     @type string $body    Email message body.
2593                  *     @type string $headers Any email headers. Default empty.
2594                  * }
2595                  * @param int   $failures The number of failures encountered while upgrading.
2596                  * @param mixed $results  The results of all attempted updates.
2597                  */
2598                 $email = apply_filters( 'automatic_updates_debug_email', $email, $failures, $this->update_results );
2599
2600                 wp_mail( $email['to'], wp_specialchars_decode( $email['subject'] ), $email['body'], $email['headers'] );
2601         }
2602 }