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